MVC Action isn't triggered in controller

后端 未结 1 1429
一生所求
一生所求 2020-12-07 05:14

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

View:

@model IEnumerable
 @foreach (var item in Model)
    {
      @H         


        
相关标签:
1条回答
  • 2020-12-07 05:54

    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%" />
    }
    
    0 讨论(0)
提交回复
热议问题