I have a question. I need to save all values of my model.
In index.cshtml, I have :
@model IEnumerable
I can get all my values in foreach in my view.
@foreach (var item in Model) {
item.ID, item.Name
}
But I need to pass my entire Model to my controller with ONE link :
html.actionlink("Save It", Save, ...);
How can I do that please ?
Thanks
You cannot pass an entire model with a GET request like this. You could use an HTML form:
@using (Html.BeginForm("Save", "SomeController"))
{
@Html.EditorForModel()
<input type="submit" value="Save It">
}
where you have defined an editor template for this model (~/Views/Shared/EditorTemplates/Item.cshtml
) which uses hidden fields:
@model Item
@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.Name)
The name and location of this partial is important. It should be located in ~/Views/Shared/EditorTemplates
and the filename should be called Item.cshtml
if Item is the type name of your model collection i.e. IEnumerable<Item>
. The editor template will be executed for each item of the collection and render the corresponding hidden fields that will allow to transport it to the server.
This form will successfully send the collection of items to the following controller action:
[HttpPost]
public ActionResult(IEnumerable<Item> model)
{
...
}
And here's an alternative way to proceed. If the user is not supposed to modify the model values on the view then you could simply use some unique identifier allowing you to refetch the model from wherever you fetched it initially. So for example:
public ActionResult Index(int id)
{
IEnumerable<Item> model = ... fetch the model using the id
return View(model);
}
and in the view generate a link passing this id:
@Html.ActionLink("Save It", Save, new { id = "123" })