HTTPPOST中的MVC Model为null

时间:2014-10-21 17:09:40

标签: c# model-view-controller

关于这个问题已经有很多问题,但是尽管看了很多问题,但我很难看到问题出在哪里。当我提交以下表单时,模型为空。我在这里做错了什么建议?

模型(部分):

public class ItemHeader
{
    public string hdr_contact_name { get; set; }
    public string hdr_contact_method { get; set; }
}

控制器:

   public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }

        int id2 = (int)id;            
        DB db = new DB();
        ItemHeader itemHeader = db.GetHeader(id2);
        if (itemHeader == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }
        else
        {
            return View(itemHeader);
        }      
    }
    [HttpPost]
    public ActionResult Details(ItemHeader itemHeader)
    {
        string test;
        DB db = new DB();
        Response.Write(db.UpdateHeader(itemHeader));
        Response.End();
        return null;
    }

查看(部分):

@model MVCTest2.Models.ItemHeader
    @{ Html.EnableClientValidation(true); }
    @using (Html.BeginForm())
    { 
        <table>
            <tr>
                <td>Vendor Contact</td>
                <td>@Html.TextBoxFor(model => model.hdr_contact_name, new { style = "width:24em", maxlength = 40 })</td>
                <td>Email/Phone</td>
                <td>@Html.TextBoxFor(model => model.hdr_contact_method, new { style = "width:24em", maxlength = 40 })</td>
            </tr>
        </table>         
        <input type="submit" value="Submit" />
    }

Html(部分):

<div>
<form action="/MVCTest2/VendorItem/Details/69" method="post">    
    <h4>Item Request Details</h4>
    <hr />
    <table>
       <tr>
          <td>Vendor Contact</td>
          <td><input id="hdr_contact_name" maxlength="40" name="hdr_contact_name" style="width:24em" type="text" value="" /></td>
          <td>Email/Phone</td>
          <td><input id="hdr_contact_method" maxlength="40" name="hdr_contact_method" style="width:24em" type="text" value="" /></td>
        </tr>
    </table>
    <p>
        <input type="submit" value="Submit" />
        &nbsp;&nbsp;
    </p>
</form></div>

1 个答案:

答案 0 :(得分:5)

表单已发布到/MVCTest2/VendorItem/Details/69,但操作方法POST Details没有id参数。

尝试使用此而不是实际拥有的内容:

[HttpPost]
public ActionResult Details(int? id, ItemHeader itemHeader)
{
    string test;
    DB db = new DB();
    Response.Write(db.UpdateHeader(itemHeader));
    Response.End();
    return null;
}