[英]MVC Button is not firing ActionResult
最近我开始使用studiyng MVC应用程序,到目前为止我一直坚持这个。
我有这个.cshtml代码:
@model Vidly.ViewModels.NewCustomerViewModel
@{
ViewBag.Title = "NewCustomer";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
@using (Html.BeginForm("Save", "Customers",FormMethod.Post,null))
{
<form class="form-group">
@Html.LabelFor(m => m.Customer.Name)
@Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" })
</form>
<form class="form-group">
@Html.LabelFor(m => m.Customer.Birthdate)
@Html.TextBoxFor(m => m.Customer.Birthdate, new { @class = "form-control" })
</form>
<form class="checkbox">
<label>
@Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsletter, new { @class = "form-control" }) Subscribed to Newsletter
</label>
</form>
<form class="form-group">
@Html.LabelFor(m => m.Customer.MembershipTypeId)
@Html.DropDownListFor(m => m.Customer.MembershipType, new SelectList(Model.MembershipTypes, "Id", "Name"), "Select Membership Type", new { @class = "form-control" })
</form>
@Html.HiddenFor(m => m.Customer.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
它引用了CustomersControler.cs文件中的此操作:
[HttpPost]
public ActionResult Save(Customer customer)
{
if (customer.Id == 0)
_context.Customers.Add(customer);
else
{
var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);
customerInDb.Name = customer.Name;
customerInDb.Birthdate = customer.Birthdate;
customerInDb.MembershipTypeId = customer.MembershipTypeId;
customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
}
_context.SaveChanges();
return RedirectToAction("Customers", "Index");
}
}
问题是,当我尝试单击“保存”按钮时,它根本不会触发Save ActionResult。 我已经尝试在调试模式下启动并在代码上设置断点,但它实际上并没有触发该方法。 我已经读过它与在ActionResult之前触发的JQuery事件有关,但我不知道如何阻止它(如果JQuery真的有关于此的事情)
有任何想法吗? 拜托,我真的坚持了!
视图中的模型是NewCustomerViewModel
因此绑定的模型必须相同(或者您需要使用BindAttribute
的Prefix
属性)。
将方法的签名更改为
public ActionResult Save(NewCustomersViewModel model)
此外,您需要删除所有<form>
元素( BeginForm
生成的元素除外),因为嵌套表单是无效的html。
但是,您的代码表明您的视图模型包含Customer
数据模型的属性,这是不好的做法。 视图模型应仅包含视图中所需的数据模型的属性。 然后,您将视图模型的属性映射到数据模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.