开发者

Changing the underlying model that ModelState is validating against

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 (S开发者_StackOverflow中文版tring.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.


Use this to validate any model:

var isOriginalModelValid = this.TryValidateModel(updated);

There still might be some fundamental design issues that you have though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜