2014-09-26 151 views
0

我有一個表格來管理的意見插入:重定向後登錄無法工作

@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); 
    } 

enter image description here

記錄

enter image description here

重定向URL將被評論/創建和將失敗,一個404錯誤,確實存在管理這個問題的通用解決方案,因爲我不能用一個簡單的重定向操作?

+0

工作時,您所提交的表單目標行動是不是調用它給404沒有找到? – 2014-09-26 11:04:46

+0

@Kartikeya我已經更新了錯誤 – InferOn 2014-09-26 11:17:20

+0

而不是'return RedirectToLocal(returnUrl);'try'return RedirectToAction(「Create」,「Comments」);' – 2014-09-26 11:21:54

回答

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 }); 
    } 

...並像一個魅力