2010-12-16 21 views
0

我将较大的模型推送到视图,但只想更新该视图的部分视图,该视图具有多个部分视图。更改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); 
    // } 

}

我想运行反对 “更新” 而不是 “sectionUpdates” 上述验证。

我有原始信息更新正常,但需要对原始运行验证,而不是sectionUpdates ..就好像已经有a.Prop1一样,视图中没有输入字段。它相对较大,并且不希望将大量隐藏的字段发送回服务器而不需要。

+0

我很困惑。 *为什么*你不想验证*更新*模型?如果原始模型没有改变,为什么要麻烦验证它? – TheCloudlessSky 2010-12-16 18:31:46

+0

@TheCloudlessSky原始版现在更新为更新问题部分。 – Tracker1 2010-12-16 18:47:24

+0

我明白你的意思了。看到我的帖子下面。 – TheCloudlessSky 2010-12-16 19:07:04

回答

3

用来验证任何型号:

var isOriginalModelValid = this.TryValidateModel(updated); 

还有可能是你,虽然有一些基本的设计问题。

+0

我不明白为什么这个工作,但它确实。任何人都可以解释为什么这有效吗谢谢CloudLessSky! – 2013-06-28 05:39:53

+0

@Chris - 查看[MVC源代码](http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Controller.cs)中的TryValidateModel的来源。您可以看到它将使用ModelMetadata的每个'ModelValidators'验证指定的模型。 – TheCloudlessSky 2013-06-28 08:57:26

+0

谢谢CloudLessSky - 非常方便! – 2013-07-02 22:59:25