Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-mvc-viewmodelmodelbinders

Can I use ModelBinder to get object without adding parameter to action?


I am new in MVC. I have a view that contains many dropdowns and viewmodel with many lists. Most of these lists are static so I want to cache retrived records. I can do this with (custom) Model binders, but I dont like that to actually use (custom) Model Binder I need to add parameter for every object in Action method like this:

public ViewResult SubmitNewValue(MyViewModel viewMod, IEnumerable<List1> list1, IEnumerable<List2> list2, IEnumerable<List3> list3 ...)
{
viewMod._list1 = list1;
viewmod._list2 = list2;
viewMod._list3 = list3;
...
return View(viewMod);
}

What I think would look better is something like:

public ViewResult SubmitNewValue(MyViewModel viewMod)
{
viewMod._list1 = ModelBinders.GetInstanceFor<List1>();
viewmod._list2 = ModelBinders.GetInstanceFor<List2>();
viewMod._list3 = ModelBinders.GetInstanceFor<List3>();
//I am able to wrap above to separate function like PrepareViewModel(viewMod)
...
return View(viewMod);
}

Is there a function/way to do this?

I am also not sure if I chose good approach but my viewmodel is losing lists for dropdowns, so I need to somehow readd them to ViewModel after [HttpPost] for example.


Solution

  • The modelbinder's sole job is to bind data from the request (querystring or post body) to parameters on your action method. So, no, if there's no parameter, the modelbinder does nothing with the data.

    You can access the data directly from the request, i.e. Request["list1"]. However, that's the raw data as the modelbinder would receive it, before it actually did any of the work it does. In other words, you would need to manually do type-coercion or new up things, etc., with that data.

    That said, this sounds like an XY problem. What is it that you're actually trying to achieve, because there's probably a better way.