从具有内部复杂类型的表单帖子绑定视图模型
好的,我得到了一个视图模型,如下所示:
public class PageViewModel
{
public Item Item { get; set; }
...
public PageViewModel
{ }
public PageViewModel(Item itemWebPage)
{
...
}
}
我使用表单来编辑此项目,使用的路线如下: /Controller/Edit/43
控制器使用以下代码:
[AcceptVerbs("GET")]
public new ActionResult Edit(int id)
{
...
PageViewModel pageViewModel = new PageViewModel(...);
return PartialView(pageViewModel);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, PageViewModel item)
{
if (ModelState.IsValid)
{
...
// Here, the item.Item.ID is null, I want it to map to the id of the route.
}
return PartialView("Edit", item);
}
我想要实现的是属性的 ID:item.Item.ID 绑定到 (route)URL 中的 ID。但是我无法让它工作。我尝试使用 [Bind()] 属性。
我现在使用表单中的隐藏字段修复了它,如下所示:
<%= Html.HiddenFor(model => model.Item.ID)%>
然而,这感觉有点恶心。我想知道是否有更好的更清洁的方法来做到这一点?
Ok, i got a viewmodel as follows:
public class PageViewModel
{
public Item Item { get; set; }
...
public PageViewModel
{ }
public PageViewModel(Item itemWebPage)
{
...
}
}
I use a form to edit this Item using a route like:
/Controller/Edit/43
The controller uses this code:
[AcceptVerbs("GET")]
public new ActionResult Edit(int id)
{
...
PageViewModel pageViewModel = new PageViewModel(...);
return PartialView(pageViewModel);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, PageViewModel item)
{
if (ModelState.IsValid)
{
...
// Here, the item.Item.ID is null, I want it to map to the id of the route.
}
return PartialView("Edit", item);
}
What I want to achieve is the ID of the property: item.Item.ID to be bound to the ID from the (route)URL. However I can't get it to work. I tried using [Bind()] attribute.
I fixed it now using a hidden field in the form like so:
<%= Html.HiddenFor(model => model.Item.ID)%>
However this feels a bit icky. I'd like to know if there is a better cleaner way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我个人会在表单声明中设置 ID 参数,如下所示:
Personally I would set the ID parameter in the form declaration as follows: