2011-12-03 85 views
0

我有問題讓我的視圖顯示。我創建一個鏈接 @ Html.ActionLink(「添加用戶」,「註冊」,「帳戶」)帳戶註冊不工作ASP.NET MVC

但是當我點擊它,我得到這個消息:

資源無法找到。 描述:HTTP 404.您正在查找的資源(或其某個依賴項)可能已被刪除,名稱已更改或暫時不可用。請檢查以下網址並確保它拼寫正確。

請求的URL:/帳號/註冊

這是我的觀點:

@model ContactWeb.Models.SimpleUser 
@{ 
ViewBag.Title = "CreateUser"; 
} 
<h2>Create User</h2> 
@using (Html.BeginForm()) { 
@Html.ValidationSummary(true); 
<fieldset> 
    <legend>Create User</legend> 

     <div> 
     @Html.LabelFor(c=>c.Username, "User Name") 
     @Html.TextBoxFor(c=>c.Username) 
     @Html.ValidationMessageFor(c=>c.Username) 
     </div> 

     <div> 
     @Html.LabelFor(c=>c.Password, "Password") 
     @Html.TextBoxFor(c=>c.Password) 
     @Html.ValidationMessageFor(c=>c.Password) 
     </div> 

     <div> 
     @Html.LabelFor(c=>c.ConfirmPassword, "Confirm Password") 
     @Html.TextBoxFor(c=>c.ConfirmPassword) 
     @Html.ValidationMessageFor(c=>c.ConfirmPassword) 
     </div> 
    <p> 
     <input type="submit" value="Register" /> 
    </p> 
</fieldset> 
} 
<div> 
    @Html.ActionLink("Back to List", "List") 
</div> 

和我的控制器是

 [HttpPost] 
    public ActionResult Register(RegisterModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      // Attempt to register the user 
      MembershipCreateStatus createStatus; 
      Membership.CreateUser(model.UserName, model.Password, null, null, null, true, null, out createStatus); 

      if (createStatus == MembershipCreateStatus.Success) 
      { 
       FormsAuthentication.SetAuthCookie(model.UserName, false); 
       return RedirectToAction("List", "Contact"); 
      } 
      else 
      { 
       ModelState.AddModelError("", "The username or password provided is incorrect."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    }  

回答

1

register行動飾有[HttpPost]屬性,這意味着行動只能處理 HTTP POST請求。普通鏈接產生GET請求,並且因爲沒有GET處理程序,所以你會得到404 - 找不到。若要解決此問題,請創建另一個處理GET請求的操作

[HttpGet] 
public ActionResult Register() 
{ 
    return View(); 
} 

此操作將返回頁面,其上註冊表單。

+0

我試過這個,但得到錯誤:AccountController已經定義了一個名爲'Register'的成員,其參數類型相同 – multiv123

+0

我刪除了HttpPost和它現在似乎正常工作。只有當用戶名不在系統中時,我才需要顯示鏈接。我在我的SQL數據訪問層中有一個名爲UsernameExists的方法,我想在AccountController中使用它,但它不會讓我。我會怎麼做呢?或者我可以在視圖中添加一些邏輯來做到這一點。 – multiv123

+0

對不起,已經定義了錯誤,我只是忘記從示例中刪除模型參數。查看更新。你怎麼能沒有授權檢查用戶名?我的意思是,你應該總是顯示鏈接,直到用戶登錄。 – archil

2

你想初始GET請求Register方法的重載,但它不應該有任何參數:

[HttpGet] 
public ActionResult Register() 
{ 
    return View(new RegisterModel()); 
} 

[HttpPost] 
public ActionResult Register(RegisterModel model) 
{ 
    // your existing implementation here that 
    // checks ModelState and creates the user record 
} 

這將允許顯示形式與空/默認值首先加載/Account/Register時URL。這將阻止「已經定義了一個具有相同參數類型的方法」,從而允許編譯代碼。另外,我認爲你會發現只有一個Register方法沒有HttpPost屬性,因爲它允許你有一個單獨的POST-only方法來實現回發邏輯,以及一個更簡單的僅用於初始顯示的GET方法。你甚至可以自定義只有GET的顯示,以使用特定的初始值填充模型/視圖等。

+0

太棒了!謝謝!!!只有當用戶名不在數據庫中時,我需要在我的視圖中顯示「添加爲用戶」鏈接,不太確定如何執行此操作。 – multiv123