简体   繁体   中英

Controller receives null/zero value from a View in MVC4

Here is my code:

Controller:

public ActionResult InsertData(CoModel coModel)
{
    if (ModelState.IsValid)
    {
        db.Entry(coModel).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(coModel);
}   

Model:

public class CoModel
{
    [Key]
    public int id { get; set; }      
    public string item_no { get; set; }       
    public string destination { get; set; }      
    public int total_piece { get; set; }
}   

View:

@using (Html.BeginForm("InsertData", "ControllerName", FormMethod.Post, new { Id = "Form1"}))
{
    @foreach (var item in Model)
    {
        @Html.DisplayFor(modelItem => item.item_no)  @Html.HiddenFor(model => item.item_no)
        @Html.DisplayFor(modelItem => item.destination) @Html.HiddenFor(model => item.destination) 
        @Html.DisplayFor(modelItem => item.total_piece) @Html.HiddenFor(model => item.total_piece)
        <button type="submit">Save</button>
    }
}

Here is my question. Why every time I pressed the Save button the controller receives null/zero value? Is my coding wrong?

You are using DisplayFor that is hidden. You must use EditorFor, TextBox, TextBoxFor, TextArea and others that render input HTML type different of hidden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM