0

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.

Tracker1
  • 19,103
  • 12
  • 80
  • 106

1 Answers1

3

Use this to validate any model:

var isOriginalModelValid = this.TryValidateModel(updated);

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

TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116
  • I don't understand why this works but it does. Can anyone explain why this works? Thanks CloudLessSky! – Rusty Nail Jun 28 '13 at 05:39
  • @Chris - Look at the source of the the `TryValidateModel` from [the MVC source code](http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Controller.cs). You can see that it will validate the specified model with each of the `ModelValidators` for the `ModelMetadata`. – TheCloudlessSky Jun 28 '13 at 08:57
  • Thanks CloudLessSky - Very handy! – Rusty Nail Jul 02 '13 at 22:59