【发布时间】:2018-04-15 09:34:43
【问题描述】:
混合使用命名路由和标准常规路由的属性。
我有一个UserController 有两个“创建”操作。一个是HTTPGet 用于获取视图,一个是HTTPPost 用于发回数据。
这是整个控制器:
[RoutePrefix("User")]
public class UserController : Controller {
public UserController() {}
[HttpGet]
public ActionResult Create() {
return View();
}
[Route("Create")]
[HttpPost]
public async Task<ActionResult> CreateAsync(UserM m) {
if (!ModelState.IsValid) {
return View(m);
}
var user = new User() {
Email = m.Email,
Forename = m.Forename,
IsActive = true,
Surname = m.Surname
};
return Redirect("");
}
}
但是,当我尝试从网站上的提交按钮导航到用户/创建以将数据发回时,我得到了 404。
这里是路线配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Turn on attribute routing in the controllers
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
这是回发数据的视图:
@model MyApp.WebMS.Models.UserM
@{
ViewBag.Title = "Create User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row">
<div class="xs-12">
<h3>Create User</h3>
<hr class="no-top-margin" />
</div>
</div>
@using (Html.BeginForm()) {
<div class="row">
<div class="col-sm-4">
<h4>Personal Information</h4>
<div class="user-creation-section">
<div class="form-group">
@Html.LabelFor(m => m.Forename, new { @class = "form-label" })
@Html.TextBoxFor(m => m.Forename, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Surname, new { @class = "form-label" })
@Html.TextBoxFor(m => m.Surname, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "form-label" })
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
</div>
<div class="col-sm-4">
<h4>Job Information</h4>
<div class="user-creation-section">
<div class="form-group">
@Html.LabelFor(m => m.JobTitle, new { @class = "form-label" })
@Html.TextBoxFor(m => m.JobTitle, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.StartDate, new { @class = "form-label" })
@Html.TextBoxFor(m => m.StartDate, new { type = "date", @class = "form-control" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="xs-12 pull-right">
<input type="button" class="btn" value="Back" onclick="location.href='@Url.Action("Index", "Home")'" />
<button type="submit" class="btn btn-primary">Create</button>
</div>
</div>
}
</div>
【问题讨论】:
-
你是如何在你的视图中定义
<form>的 -
是的,视野很好。
-
我问的是如何,而不是如果:)
-
哦,我的错,我会编辑 OP
-
@BenDonnelly,我已经测试了您的代码并且工作正常。这可能不是您正在运行的吗?例如,您的操作方法末尾是否有
return Redirect("");?
标签: c# .net asp.net-mvc asp.net-mvc-routing