【发布时间】:2019-05-07 23:33:33
【问题描述】:
我目前正在通过观看视频教程学习 MVC 5。我创建了一个具有两种操作方法的简单客户控制器,即(AddCustomer 和 Submit)。在这里,我为 AddCustomer 创建了一个简单的视图,并为 Showing customer data 创建了一个强类型视图。当我启动应用程序时,它会显示客户数据输入屏幕,但是当我单击提交按钮时,我遇到了错误。 你能告诉我下面的代码有什么问题吗?
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 }
);
}
【问题讨论】:
-
将
[HttpPost]属性放在Submit操作之上。乍一看,我看到表单动作有POST方法,因此[HttpPost]属性是强制性的。 -
@TetsuyaYamamoto 感谢您的快速回复。但它不起作用。仍然显示上述错误。
-
由于这是 MVC,您应该使用带有控制器名称的
BeginForm助手和带有FormMethod.Post参数的操作名称 - 避免手动创建<form>标签。
标签: asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-5 asp.net-mvc-routing