MVC动作不触发控制器 [英] MVC Action isn't triggered in controller

查看:129
本文介绍了MVC动作不触发控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个模型,一些领域和视图按钮:

I made a model, some fields and a button in the 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%" />

控制器:

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

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

问题是:

为什么保存操作,则不会触发?

Why the "Save" action isn't fired?

推荐答案

您需要一个&LT;形式为GT; 元素,以便回你的控件。你的情况,你需要指定动作的名称,因为它不一样的方法泰德产生的视图(指数()

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
}

现在,这将回发到你的保存()方法,但该模型将是空的,因为你的的foreach 循环产生重复的名称没有索引意味着它们不能被绑定到一个集合属性(因为重复的 ID 属性)。

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).

您需要使用循环(模型必须实施的IList )或自定义的 EditorTemplate 类型的员工

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

使用for循环

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

使用EditorTemplate

/Views/Shared/EditorTemplates/Employee.cshtml

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

和在主视图

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

这篇关于MVC动作不触发控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆