为什么在我的ASP.NET MVC应用程序编辑code不工作? [英] Why is the Edit code in my ASP.NET MVC application not working?
问题描述
由于某些原因,编辑作用下得到编辑视图的形式很好,但是当我点击提交我的视图页面上张贴下面的第二种方法,companyToEdit结构不包含companyID,我得到一个异常。因为,我已经这样做过,我得到在其他情况下,id字段这很奇怪。
如果我把在视图下方code的部分:
< P>
<标签=CompanyID> CompanyID:LT; /标签>
&所述;%= Html.TextBox(CompanyID,Model.CompanyID)%GT;
&所述;%= Html.ValidationMessage(CompanyID,*)%>
&所述; / P>
然后,它会工作得很好。但是,如果我身上拿走,因为CompanyID是一个只读字段它停止工作。任何想法?
//
// GET:/公司/编辑/ 5 公众的ActionResult编辑(INT ID)
{
变种companyToEdit = _repository.GetCompany(ID);
返回查看(companyToEdit);
} //
// POST:/公司/编辑/ 5 的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult编辑(INT ID,公司companyToEdit)
{
如果(!ModelState.IsValid)
返回查看();
尝试
{
_repository.Update(companyToEdit);
返回RedirectToAction(「指数」);
}
抓住
{
返回查看();
}
}
编辑2:
我想我可以做一些类似的,藏在类似下面的散列值的ID。我认为这将是最终的解决方案,我们将获得最安全和降低复杂性。
<输入ID =FKEYNAME =FKEY类型=隐藏值=4a3d337bf38b35e9ff4167cfa878160b>
您必须在编辑表单上的id字段
所以干脆把它像这样
<%= Html.Hidden(CompanyID,Model.CompanyID)%GT;
For some reason, the edit action below get to the edit view form fine, but when I hit submit on my view page to post on the second method below, the companyToEdit structure do not contain the companyID and I get an exception. This is weird since, I have done this before and I get the id field in other instances.
If I put in the view the section of code below:
<p>
<label for="CompanyID">CompanyID:</label>
<%= Html.TextBox("CompanyID", Model.CompanyID) %>
<%= Html.ValidationMessage("CompanyID", "*") %>
</p>
Then it will work just fine. But if I take that away, since the CompanyID is a read-only field it stops working. Any ideas?
//
// GET: /Company/Edit/5
public ActionResult Edit(int id)
{
var companyToEdit = _repository.GetCompany(id);
return View(companyToEdit);
}
//
// POST: /Company/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Company companyToEdit)
{
if (!ModelState.IsValid)
return View();
try
{
_repository.Update(companyToEdit);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
EDIT 2: I guess I can do something similar to this, and hide the ID in a hash value like the one below. I think this will be the ultimate solution, where we will get the most secure and the less complexity.
<input id="fkey" name="fkey" type="hidden" value="4a3d337bf38b35e9ff4167cfa878160b">
you must have the id field on the edit form so just put it like this
<%=Html.Hidden("CompanyID",Model.CompanyID) %>
这篇关于为什么在我的ASP.NET MVC应用程序编辑code不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!