Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I made a model, some fields and a button in the view:

View:

@model IEnumerable<EnrollSys.Employee>
 @foreach (var item in Model)
    {
      @Html.TextBoxFor(modelItem => modelItem.name)
    }
<input type="submit" value="Save" class="btn btn-default" style="width: 20%" />

Controller:

   public ActionResult Index()
        {
            var model = selectModels();
            return View(model);
        }

        [HttpPost]
        public ActionResult Save(IEnumerable<EnrollSys.Employee> model)
        {
            return View();
        }

The problem is:

Why the "Save" action isn't fired?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need a <form> element to post back your controls. In your case you need to specify the action name because its not the same as the method thet generated the view (Index())

@using (Html.BeginForm("Save"))
{
   .... // your controls and submit button
}

This will now post back to your Save() method, however the model will be null because your foreach loop is generating duplicate name attributes without indexers meaning that they cannot be bound to a collection (its also creating invalid html because of the duplicate id attributes).

You need to use a for loop (the model must implement IList) or a custom EditorTemplate for type of Employee.

Using a for loop

@model IList<EnrollSys.Employee>
@using (Html.BeginForm("Save"))
{
  for (int i = 0; i < Model.Count; i++)
  {
    @Html.TextBoxFor(m => m[i].name)
  }
  <input type="submit" value="Save" class="btn btn-default" style="width: 20%" />
}

Using an EditorTemplate

In /Views/Shared/EditorTemplates/Employee.cshtml

@model EnrollSys.Employee
@Html.TextBoxFor(m => m.name)

and in the main view

@model IEnumerable<EnrollSys.Employee> // can be IEnumerable
@using (Html.BeginForm("Save"))
{
  @Html.EditorFor(m => m)
  <input type="submit" value="Save" class="btn btn-default" style="width: 20%" />
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...