如何在asp.net mvc3中向TryUpdateModel添加绑定列表
我有以下操作方法:-
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Assessment a = elearningrepository.GetAssessment(id);
try
{
if (TryUpdateModel(a))
{
elearningrepository.Save();
return RedirectToAction("Details", new { id = a.AssessmentID });
}
}
//code does here
但我不能编写类似 if (TryUpdateModel(a, "Assessment", new string { "Date"}))
的内容来指定我只允许 Date 属性有待更新。 那么我如何向上面添加绑定列表 if (TryUpdateModel(a))
?
BR
I have the following action method:-
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Assessment a = elearningrepository.GetAssessment(id);
try
{
if (TryUpdateModel(a))
{
elearningrepository.Save();
return RedirectToAction("Details", new { id = a.AssessmentID });
}
}
//code does here
but I can not write something like if (TryUpdateModel(a, "Assessment", new string { "Date"}))
to specify that I only allow the Date property to be updated.
So how I can add a bind list to the above if (TryUpdateModel(a))
?
BR
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是因为你应该这样写,因为允许的属性参数代表一个字符串大批:
That's because you should write it like this, since the allowed properties argument represents a string array:
我建议您一般不要使用 TryUpdateModel。
存储库通常有一个更新方法,可以在调用 Save() 之前将实体状态设置为修改,我在上面的代码中看不到这一点。
如果您的目标是显示记录并且只允许保存日期,则为该模型创建一个视图,并使用以下方式渲染字段:
这将设置视图的模型:
@Html.DisplayFor(model=>model .propertyToDisplay)
在您只想显示的项目上,并且 a
在您的操作控制器中,您将要绑定的属性作为输入参数:
已编辑
在这种情况下,模型绑定器应该只需绑定到 Id 和 Date,所以即使有人尝试发布其他值(编辑 html 表单很容易),ActionResult 中的参数也应该与模型中的参数完全一样命名,并使用它来获取和更新实体。
您应该验证用户是否确实可以访问和编辑该 id,或者作为替代方法使用 MVC Security Codeplex 来检查说明Id参数没有被篡改。使用起来确实简单方便,但那是另一个讨论了。
作为替代方案,您可以使用类似的属性,如 这个博客,但我自己不使用它:
I would suggest that you stay away from using TryUpdateModel in general.
The repository usually has an update method that sets the entityState to modified before Save() is called, i cannot see that in the code above.
If your goal is to display a record and only allow date to be saved, then create a view for that model, and render fields with:
This sets the model for the view:
@Html.DisplayFor(model=>model.propertyToDisplay)
on the items you only want to display, and a
In your action controller you take the properties you want to bind to as input parameters:
Edited
In this case the model binder should just bind to Id, and Date, so even if someone tries to post other values (editing the html form is easy), parameters in ActionResult should be named exactly as in the Model and use that to fetch and update the entity.
You should validate that the user actually can access and edit that id, or as an alternative use MVC Security Codeplex to check that the Id parameter has not been tampered with. it is really easy and convenient to use, but that is another discussion.
As an alternative you can use an attribute like this, described in this blog, but I don't use that myself:
我试过了,效果很好
i tried this an it works fine