ASP.NET MVC, passing Model from View to Controller

Cabadath picture Cabadath · May 30, 2012 · Viewed 7.9k times · Source

I'm having trouble with ASP.NET MVC and passing data from View to Controller. I have a model like this:

 public class InputModel {
   public List<Process> axProc { get; set; }

   public string ToJson() {
     return new JavaScriptSerializer().Serialize(this);
   }
 }

 public class Process {
   public string name { get; set; }
   public string value { get; set; }
 }

I create this InputModel in my Controller and pass it to the View:

public ActionResult Input() {
  if (Session["InputModel"] == null)
    Session["InputModel"] = loadInputModel();
  return View(Session["InputModel"]);
}

In my Input.cshtml file I then have some code to generate the input form:

@model PROJ.Models.InputModel

@using(Html.BeginForm()) {
  foreach(PROJ.Models.Process p in Model.axProc){
    <input type="text" />
    @* @Html.TextBoxFor(?? => p.value) *@
  }
  <input type="submit" value="SEND" />
}

Now when I click on the submit button, I want to work with the data that was put into the textfields.

QUESTION 1: I have seen this @Html.TextBoxFor(), but I don't really get this "stuff => otherstuff". I concluded that the "otherstuff" should be the field where I want to have my data written to, in this case it would probably be "p.value". But what is the "stuff" thing in front of the arrow?

Back in the Controller I then have a function for the POST with some debug:

[HttpPost]
public ActionResult Input(InputModel m) {
  DEBUG(m.ToJson());
  DEBUG("COUNT: " + m.axProc.Count);

  return View(m);
}

Here the Debug only shows something like:

{"axProc":[]}
COUNT: 0

So the returned Model I get is empty.

QUESTION 2: Am I doing something fundamentally wrong with this @using(Html.BeginForm())? Is this not the correct choice here? If so, how do I get my model filled with data back to the controller?
(I cannot use "@model List< Process >" here (because the example above is abbreviated, in the actual code there would be more stuff).)

I hope someone can fill me in with some of the details I'm overlooking.

Answer

tkt986 picture tkt986 · May 30, 2012

Change your view to some thing like this to properly bind the list on form submission.

@using(Html.BeginForm()) {
  for(int i=0;i<Model.axProc.Count;i++){
   <span>
    @Html.TextBoxFor(model => model.axProc[i].value)
</span>
  }
  <input type="submit" value="SEND" />
}