Kye
Kye

Reputation: 6279

How to include all custom object property in MVC 4 HttpPost

I have a view model with a custom object. On the initial get, I populate Foo and use a couple of Foo's properties.

On the post, I find that Foo on the view model is null.

I could add to my view, @Html.HiddenFor(x => x.Foo.Id) which could ensure that a Foo is populated with at least an Id, but then I could need to add similar code for all of the properties.

Is there a way to send back the complete object?

public class RequestModel
    {
        public Foo Foo{ get; set; }

        [Required]
        [Display(Name = "Comment")]
        public string Comment { get; set; }
    }

Controller

public ActionResult Index(int? id)
{
   //Populate Foo here using EF and add it to the model
   var model = new RequestModel { Foo = foo };    
   return View(model);
}



[HttpPost]
public ActionResult Index(int? id, RequestModel model)
{
   return View(model);
}

View

@Html.DisplayTextFor(m=>m.Application.Name)

etc

Upvotes: 1

Views: 431

Answers (1)

Peter
Peter

Reputation: 7804

Add a view model with the properties you want to your solution. Put your validations etc on it and use that to move your data between your page and controller then map the properties to your EF object.

Upvotes: 1

Related Questions