Adam Stepniak
Adam Stepniak

Reputation: 877

Posting part of viewModel to post action method

I would like to know if I am doing something wrong or it is not possible to post only part of view model using default model binder. Let's say I have a complex viewmodel that only small part it should be posted. I would like to achieve something like this:

public class ComplexViewModel
{
    public object FirstNotPostedData { get; set; }
    public object SecondNotPostedData { get; set; }
    //......
    public object NthNotPostedData { get; set; }

    public InnerModelToPost InnerModelToPost { get; set; }
}

public class InnerModelToPost
{
    public string FirstProperty { get; set; }
    public string SecondProperty { get; set; }
    public string ThirdProperty { get; set; }
}

In view I would like to display part of model and post the other part:

@model ComplexViewModel
@* DISPLAYING DATA *@
<form>
    @Html.HiddenFor( m => m.InnerModelToPost.FirstProperty )
    @Html.HiddenFor( m => m.InnerModelToPost.SecondProperty )
    @Html.HiddenFor( m => m.InnerModelToPost.ThirdProperty )

    <button type="submit">Submit button</button>
</form>

And then I would like to be able to pass this model to my controller in this way using default model binder:

public ActionResult GetOnlyImportantPartOfModel( InnerModelToPost innermodel)
{
    //I'm getting empty model when I' doing like this

    return View();
}

You may ask why not to pass entire model as parameter to this action method. So the answer is: code readablity. I store ComplexViewModel in session and I read it in first line of my action method. I would like to pass only this data that I want to update my model with.

Upvotes: 1

Views: 1052

Answers (1)

user3559349
user3559349

Reputation:

Your need to use the Prefix property of [Bind] attribute to strip the InnerModelToPost prefix from your form values.

public ActionResult GetOnlyImportantPartOfModel([Bind(Prefix = "InnerModelToPost")] InnerModelToPost innermodel)
{
    ....
}

Having said that, if your only using properties of InnerModelToPost, then in your GET method, you can read the parent class (ComplexViewModel) from Session, but pass only the InnerModelToPost property to the view

Upvotes: 5

Related Questions