我有这个模型,客户。当我获得带有id的信息时,它的工作正常。
喜欢;
/客户/实体/ 5
@model ProgSpace.Models.Customer
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_MainLayout.cshtml";
}
@section bodypane
{
@using (Html.BeginForm("Entity", "Customer", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="col-md-12">
<div class="col-md-1">
<label>Customer No:</label>
<h4># @(Model.ID) </h4>
</div>
<div class="clearfix"></div><br />
<div class="col-md-2">
<div class="col-md-12">
<div class="col-md-12 fileupload fileupload-exists" data-provides="fileupload">
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 200px; height: 150px;">
<img src="@Model.Picture.Path" />
</div>
<div>
<span class="btn btn-default btn-file">
<span class="fileupload-new">Add Pic </span>
<span class="fileupload-exists">Change</span><input name="file" id="file" type="file">
</span>
<a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>
</div>
</div>
</div>
<div class="col-md-10">
<div class="col-md-3">
<label>Name *</label>
@Html.TextBoxFor(model => model.Name, new { @class = "form-control"})
</div>
<div class="col-md-3">
<label>Company</label>
@Html.TextBoxFor(model => model.Contact.Company, new { @class = "form-control"})
</div>
<div class="col-md-3">
<label>Phone </label>
@Html.TextBoxFor(model => model.Contact.Phone, new { @class = "form-control" })
</div>
</div>
<div class="clearfix"><br /></div>
<p> </p>
<div class="col-md-12">
<div class="btn-group">
<button class="btn btn-danger btn-lg">Cancel</button>
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</div>
}
}
在控制器中我有这些动作。
public ActionResult Entity(int id)
{
Customer cust= sis.Customers.Where(t => t.ID == id).FirstOrDefault();
return View(cust);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Entity(Customer cust, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
/* Do something */
}
else
{
}
return View(cust);
}
当动词是GET时,没关系。但是当我发布这个表单并且当第二个动作(HttpPost动作)启动时,视图会抛出错误..
未将对象引用设置为对象的实例
标记 Model.ID 在视图中为空。
<div class="col-md-1">
<label>Customer No:</label>
<h4># @(Model.ID) </h4> ---> THIS HERE THROWS NULL EXCEPTION
</div>
我尝试为Model.ID添加HiddenFor,如
@Html.HiddenFor(t => t.ID)
但它没有改变任何东西。
如何再次使用相同的上下文返回相同的视图?