Search code examples
c#asp.net-mvchidden-field

Hidden input for passing data to controller


I'm trying to pass the model ,that have passed to view, again to a controller.Is that possible using a Hidden attribute??

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>

<div>
    @using (Html.BeginForm("planviewCreate", "plan",System.Web.Mvc.FormMethod.Post))
    {


       @Html.HiddenFor(Model);
    }

    <input " type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">

</div>

in my controller;

public ActionResult planviewCreate(PlanObjectsViewModel model)
{
    // some code here
    return View();
}

Is this possible??


Solution

  • You will need to use a for loop and an array indexer so it knows how to map the data back to your controller.

    @model MvcApp.ViewModel.PlanObjectsViewModel[]
    
    
    @for(var i = 0; i < Model.Count(); i++)
    {
        @Html.HiddenFor(m => m[i].PropertyName1);
        @Html.HiddenFor(m => m[i].PropertyName2);
    }
    

    Controller signature

    [HttpPost]
    public ActionResult PlanviewCreate(PlanObjectsViewModel[] viewModel) //using model as the variable name will give undesired results.
    

    If you have a big model and don't want to map each property, you can serialize to xml or json and pass that as a single string to your view into a hidden field. Deserialize on the return to your controller. IMO, you should use caching if you don't want the data to be altered by the user.