Reputation: 13
I have two Viewmodels, a view and two partial views and a controller method for submit. Lets name them, BigViewModel, SmallViewModel, Page.cshtml, _Options.cshtml, _Submit.cshtml and Submit(BigViewModel) method in controller.
SmallViewModel is included in BigViewModel as one of the properties.
like,
public class BigViewModel
{
public bool Confirm { get; set; }
public SmallViewModel s { get; set; }
}
Now, Page.cshtml has a division where _Options.cshtml resides where user can input few options like sorting, searching etc. This _Options.cshtml uses a viewmodel called SmallViewModel. When you click on Submit button which is on _Options.cshtml partial view, it opens a dialog box that is _Submit.cshtml which asks for confirmation and submit button. This confirmation information is stored in BigViewModel. Now, when I hot submit it goes to Submit(BigViewModel) method in the controller.
My problem is how to include SmallViewModel data into BigViewModel from _Submit.cshtml partial view page. Because, when I go to the Submit(BigViewModel) method, I only see Confirm - True/False. But smallViewModel is null.
Hope, question is clear enough. I didn't know how else to ask. Please help.
Upvotes: 1
Views: 2018
Reputation: 2052
You can simply create an interface that all models with options will derive from. Here is a sample :
public class BigViewModel : IModelOptions
{
public bool Confirm { get; set; }
public SmallViewModel SmallView { get; set; }
}
public class SmallViewModel
{
public string Stuff{ get; set; }
}
public interface IModelOptions
{
SmallViewModel SmallView { get; set; }
}
this way if you ever need more models with options you can simple do "NewModel : IModelOptions". Now your _options view would look something like
@model MvcApplication1.Models.IModelOptions
@Html.TextAreaFor(x => x.SmallView.Stuff)
Note that now your partial view does not need to be aware of what model is being passed in. So long as it derives from IModelOptions then it knows it will have a SmallView. Our _submit would be something like
Are you sure? If so I will use fancy javascript to allow you to submit!
<input type="submit"/>
and then we tie that all together in our main view (Index , Page, what have you)
@model MvcApplication1.Models.BigViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Confirm)
{
Html.RenderPartial("_Options");
Html.RenderPartial("_Submit");
}
}
Note that here we take in a BigViewModel. That should work fine as our BigViewModel houses Options and derives from IModelOptions.
Our controller would simply be
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(BigViewModel model)
{
var smallVIewModelInfo = model.SmallView.Stuff;
var bigViewModelConfirm = model.Confirm;
return View();
}
}
and now you should be getting data from both small and big view model.
Upvotes: 1