我有一个表单来管理评论的插入:
@model GatorsWebSite.Comment
@using (Html.BeginForm("Create", "Comments", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.ArticleID)
@Html.TextAreaFor(m => m.Text, new { @class = "form-control wide", @placeholder = "Type your comment", @rows = "3" })
@Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger" })
}
这是对控制器的操作:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Text, ArticleID")] Comment comment){
if (comment == null || comment.ArticleID <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid){
comment.Date = DateTime.Now;
comment.UserID = User.Identity.GetUserId();
_commentRepository.Add(comment);
_commentRepository.Save();
}
return RedirectToAction("Details", "News", new { ID = comment.ArticleID });
}
由于操作受到授权,因此如果用户未登录
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl){
if (ModelState.IsValid){
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null){
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
重定向网址将是评论/创建,并且会因404错误而失败,是否存在管理此问题的常规解决方案,因为我无法使用简单的重定向来执行操作?
答案 0 :(得分:1)
另一种方法是进行Create
获取操作,并将其重定向到文章/新闻列表页面。例如:
public ActionResult Create(){
return RedirectToAction("Index", "News");
}
修改强>
正是我所做的:
[Authorize]
[HttpGet]
public ActionResult Create([Bind(Include = "Text, ArticleID")] Comment comment)
{
if (comment == null || comment.ArticleID <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
comment.Date = DateTime.Now;
comment.UserID = User.Identity.GetUserId();
_commentRepository.Add(comment);
_commentRepository.Save();
}
return RedirectToAction("Details", "News", new { ID = comment.ArticleID });
}
......并且像魅力一样工作