简体   繁体   English

控制器从 MVC4 中的视图接收空/零值

[英]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.您正在使用隐藏的 DisplayFor。 You must use EditorFor, TextBox, TextBoxFor, TextArea and others that render input HTML type different of hidden.您必须使用 EditorFor、TextBox、TextBoxFor、TextArea 和其他呈现输入 HTML 类型不同的隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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