2009-07-22 23 views
0

我有一個UserController和一個Edit.aspx。有一個字段是我的主鍵,所以我不想讓用戶編輯此字段。asp.net-mvc/linq to sql - 我是否總是需要一個HTML.TextBox來執行Edit Save?

的問題是,如果我刪除

 <%= Html.TextBox("Email", Model.Email) %> 

那麼當asp.net-MVC魔術叫我的控制器代碼:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Edit(int id, tblMailingList user_) 
    { 
     try 
     { 
      repo.UpdateUser(user_); 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 

的tblMailingList的電子郵件字段爲空。問題是我需要這個作爲表中的查找來檢索當前記錄,顯然如果它的空我得到一個異常。

當我把這個字段的文本框,它工作正常。看起來很瘋狂,我必須有一個文本框,並允許編輯將該字段傳遞給控制器​​。我試圖把它放在一個標籤中,它仍然在控制器中顯示爲空。

有什麼建議嗎?

回答

3

我的第一個問題是,你爲什麼要在電子郵件字段而不是Id字段上查找?

您可以將您的Form聲明中的參數傳遞給Controller。

<% using (Html.BeginForm(
    "MethodName", "Controller", FormMethod.Post, 
    new { id = Model.Id, email = Model.Email)) { %> 

我不知道如果我得到的方法聲明正確,所以請檢查。

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Edit(int id, string email, tblMailingList user_) 
{ 
    try 
    { 
     repo.UpdateUser(user_); 
     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View(); 

我會建議更新略有不同,因爲您的tblMailingList用戶將無法在您的存儲庫中更新。

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Edit(int id, FormCollection form) 
{ 
    tblMailingList user = repo.GetUser(id); // get the user using the id 
              // so we can update in the same 
              // context 
    UpdateModel(user); // this will automatically update 
         // your user model with values 
         // from the form 

    try 
    { 
     repo.UpdateUser(user); 
     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View(); 
0

如果你只是想要一個可以傳遞給控制器​​的字段,它需要在表單中不可見,Html.HiddenField可以用於你的情況。

我錯了嗎?

相關問題