Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Not Posting entire Model

I am fairly new to MVC and am really trying to a get used to the Model Binding. I have a simple model that i have created in a form. However, when i post that form ONLY the textbox values are carrying over to the controller. I need the description field also which is done using DisplayTextFor. Is this something i am going to have to make a custom model binder for? I could take a shortcut and just make the description a read only textbox with no border so it looks like text, but i want to do it the correct way. Here is my code:

public class FullOrder
{
    public List<FullOrderItem> OrderList { get; set; }
    public string account { get; set; }
    public string orderno { get; set; }
}

public class FullOrderItem
{
    public int? ID { get; set; }
    public int? OrderId { get; set; }
    public string Description { get; set; }
    public int Qty { get; set; }
    public decimal? Price { get; set; }
}

Here is the View

<table class="ExceptionAltRow">
    <tr style="background-color: #DDD;">
        <td class="strong" style="width:500px;">
            Description
        </td>
        <td class="strong" style="width:100px;">
            Qty
        </td>
        <td class="strong" style="width:100px;">
            Previous Purchases
        </td>
    </tr>
    @for (int i = 0; i < Model.FullOrder.OrderList.Count(); i++)
    {
        <tr>
            <td>
                @Html.DisplayTextFor(m => m.FullOrder.OrderList[i].Description)
            </td>
            <td>
                @Html.TextBoxFor(m => m.FullOrder.OrderList[i].Qty, new { @style = "width:50px;" })
            </td>
        </tr>
    }
    </table>

Here is the Controller:

[HttpPost]
public ActionResult AddItem(FullOrder f)
{
    //doesn't work description is not passed but qty is
}

Is there a way that i can get my Model to just simply pass on the description on a post even though it is not a textboxfor bound item from my model?

like image 237
mscard02 Avatar asked Jan 24 '12 18:01

mscard02


1 Answers

The only data that will be posted to your application is that data which is available on the form that's being submitted (unless the form fields are disabled, of course). You can override what the controller sees by implementing a custom model binder.

In this case, your form consists of many instances of a single text field:

@Html.TextBoxFor(m => m.FullOrder.OrderList[i].Qty, new { @style = "width:50px;" })

If you'd like description and other things filled out, they need to be present on the form. If they don't need to be visible, then you can use the HiddenFor helper:

@Html.HiddenFor(m => m.FullOrder.OrderList[i].Description)

See also What does Html.HiddenFor do?

like image 168
Kaleb Pederson Avatar answered Sep 28 '22 10:09

Kaleb Pederson