Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c# - MVC Action isn't triggered in controller

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

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

1 Reply

0 votes
by (71.8m points)

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%" />
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...