I have a situation where I am wanting an ‘Add’ View to accept an int from the controller but return a different type to the HttpPost controller method. Confusing, I know. The ‘Add’ View is used to create an object typed as a Widget, but I need to pass in the ID of the WidgetCategory. So in my WidgetController, I would have a method something like:
public ActionResult Add(int id) // 'id' is the WidgetCategoryID
{
return View(id);
}
However, in the view, since in it’s intended to return a Widget to be added would start like this:
@using MyProject.Models
@model Widget
@{
ViewBag.Title = "My Title";
Layout = "~/Views/Shared/_MyLayout.cshtml";
}
@using (Html.BeginForm())
{
// Insert markup here ...
}
My question is, how do I pass the WidgetCategoryID into the controller if it’s typed to return a Widget? I was hoping to add it as a hidden field inside the form like so:
@Html.Hidden(id)
Any ideas would be greatly appreciated.
Thanks!
default model binder checks for request parameters by name and attempts to set properties on model according. If you need something more evolute, you can take a look to custom model binding. Btw, you can change your action to:
or
I slightly prefer the second form for creations, but I guess it’s a matter of tastes
Btw, your view’s form shall have inputs for each “important” property of the Widget object. (Hidden or text) via: