更改 ModelState 验证所依据的底层模型
我正在将一个更大的模型推送到视图,但只想更新该视图的部分内容,该视图具有列表的多个部分视图。
本质上,我有更新原始模型的代码,但希望 ModelState.IsValid 针对更新后的原始模型而不是发布的部分进行操作。
[HttpPost]
public virtual ActionResult MyAction(MyFullModel sectionUpdates)
{
var updated = Session['original'] as MyFullModel;
for (var i=0; i<updated.Section.Count; i++)
{
var a = original.Section[i] as SubModel;
var b = sectionUpdates.Section[i] as SubModel;
if (String.IsNullOrWhiteSpace(a.Prop1))
{
a.Prop1 = b.Prop1
}
if (String.IsNullOrWhiteSpace(a.Prop2))
{
a.Prop2 = b.Prop2
}
...
}
// ??? How do I run ModelState.IsValid against original here ???
// this doesn't seem to work, the only the posted values are checked...
// ViewData.Model = model;
// ModelState.Clear();
// if (!TryUpdateModel(model))
// {
// //model state is invalid
// return View(secureFlightUpdates);
// }
}
我想针对上面的“updated”而不是“sectionUpdates”运行验证。
我的原始信息更新正常,但需要运行验证与原始内容相反,而不是sectionUpdates..就好像已经有a.Prop1一样,帖子的视图中没有输入字段。它相对较大,并且不想在不需要的情况下将大量隐藏字段发送回服务器。
I am pushing out a larger model to a view, but wanting to update only parts of that view, that has multiple partial views for a List.
Essentially, I have the code to update the original model, but want to have the ModelState.IsValid operate against the updated original model, not the posted partial.
[HttpPost]
public virtual ActionResult MyAction(MyFullModel sectionUpdates)
{
var updated = Session['original'] as MyFullModel;
for (var i=0; i<updated.Section.Count; i++)
{
var a = original.Section[i] as SubModel;
var b = sectionUpdates.Section[i] as SubModel;
if (String.IsNullOrWhiteSpace(a.Prop1))
{
a.Prop1 = b.Prop1
}
if (String.IsNullOrWhiteSpace(a.Prop2))
{
a.Prop2 = b.Prop2
}
...
}
// ??? How do I run ModelState.IsValid against original here ???
// this doesn't seem to work, the only the posted values are checked...
// ViewData.Model = model;
// ModelState.Clear();
// if (!TryUpdateModel(model))
// {
// //model state is invalid
// return View(secureFlightUpdates);
// }
}
I want to run validation against "updated" not "sectionUpdates" above.
I have the original information updating fine, but need to run the validation against the original, not the sectionUpdates.. as if there was already an a.Prop1, there's no input field in the View for the post. It's relatively large, and don't want to post a ton of hidden fields back to the server without need.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用它来验证任何模型:
但是您仍然可能遇到一些基本的设计问题。
Use this to validate any model:
There still might be some fundamental design issues that you have though.