我目前正在通过观看视频教程来学习MVC 5。我创建了一个具有两种操作方法的简单客户控制器(即AddCustomer和Submit)。在这里,我为AddCustomer创建了一个简单视图,为显示客户数据创建了强类型视图。当我启动应用程序时,它向我显示了客户数据输入屏幕,但是当我单击“提交”按钮时,出现了以下错误。 您能告诉我下面的代码是什么问题吗?
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Submit
这是我的客户控制代码:-
public class CustomerController : Controller
{
// GET: Customer
public ActionResult AddCustomer()
{
return View();
}
public ActionResult Submit(Customer objcust)
{
objcust.CustomerID = Request.Form["txtcustid"];
objcust.CustomerName = Request.Form["txtcustname"];
return View("ShowCustData", objcust);
}
}
这是我的ShowCustData视图:-
@model DataAnnotationsEx.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowCustData</title>
</head>
<body>
<div>
Customer ID: @Model.CustomerID <br />
Customer Name: @Model.CustomerName
</div>
</body>
</html>
这是我的AddCustomer视图:-
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddCustomer</title>
</head>
<body>
<div>
<form action="Submit" method="post">
Customer ID: <input id="Text1" type="text" name="txtcustid" /><br />
Customer Name: <input id="Text1" type="text" name="txtcustname" /><br />
<input id="Submit1" type="submit" value="submit" />
</form>
</div>
</body>
</html>
这是我的客户模型:-
public class Customer
{
[Required]
[StringLength(7)]
[RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string CustomerID { get; set; }
[Required]
[StringLength(10)]
public string CustomerName { get; set; }
}
这是我的Route.config:-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action = "AddCustomer", id = UrlParameter.Optional }
);
}
答案 0 :(得分:1)
问题是您的Submit
控制器操作没有[HttpPost]
属性,您的表单方法定义为POST
。您应该在相应的操作方法上添加提到的属性:
[HttpPost]
public ActionResult Submit(Customer objcust)
{
objcust.CustomerID = objcust.CustomerID;
objcust.CustomerName = objcust.CustomerName;
return View("ShowCustData", objcust);
}
请注意,默认情况下,如果未指定[HttpPost]
属性,它将自动设置为GET方法,因此表单提交请求永远无法达到该操作方法。
然后,您应将<form>
标签替换为Html.BeginForm()
帮助器,并使用如下类型的强类型视图模型定义:
@model Customer
@using (Html.BeginForm("Submit", "Customer", FormMethod.Post))
{
@Html.LabelFor(model => model.CustomerID)
@Html.TextBoxFor(model => model.CustomerID)
@Html.LabelFor(model => model.CustomerName)
@Html.TextBoxFor(model => model.CustomerName)
<input id="Submit1" type="submit" value="submit" />
}
通过使用强类型的viewmodel类,文本框将自动绑定到viewmodel属性,并能够在表单提交期间检索值。