2009-08-08 21 views
3

我知道,使用jEditable(http://www.appelsiini.net/projects/jeditable),您可以進行就地編輯並將更改後的信息發佈到URL。在ASP.NET MVC中使用jEditable(POSTing)

我的ASP.NET MVC視圖顯示了一堆模型信息,我想就地編輯。目前,我有兩個視圖 - 一個文本表示和一個編輯視圖,其中一個表單完全發佈,然後我的控制器操作將整個對象(從表單元素名稱組合而成)作爲參數,更新對象並返回文本 - 僅查看。

但是,當我切換到jEditable時,我一次只能使用文本視圖並POST一個項目,而不是整個對象。我怎麼能建立一個單一的控制器動作,可以採取什麼jEditable張貼,然後把它放入我的對象的適當屬性?

回答

8

有一些不錯sample code here

$("#myTextBox").editable('<%=Url.Action("UpdateSettings","Admin") %>', { 
      submit: 'ok', 
      cancel: 'cancel', 
      cssclass: 'editable', 
      width: '99%', 
      placeholder: 'emtpy', 
      indicator: "<img src='../../Content/img/indicator.gif'/>" 
     }); 


[AcceptVerbs("POST")] 
public ActionResult UpdateSettings(string id, string value) 
{ 
    // This highly-specific example is from the original coder's blog system, 
    // but you can substitute your own code here. I assume you can pick out 
    // which text field it is from the id. 
    foreach (var item in this.GetType().GetProperties()) 
    { 

     if (item.Name.ToLower().Equals(id, StringComparison.InvariantCultureIgnoreCase)) 
      item.SetValue(Config.Instance, value, null); 
    } 
    return Content(value); 
} 

您可能還需要這樣的:
http://noahblu.wordpress.com/2009/06/17/jeditable-note-dont-return-json-and-how-to-return-strings-from-asp-net-mvc-actions/

+1

但是如果我有一個大型模型,比如有20個屬性會怎樣。我需要20種不同的控制器方法嗎?或者如果我使用了一個通用的id/value參數對,那麼我如何讓這個值自動更新正確的對象屬性? – Alex 2009-08-08 21:22:50

+0

原始代碼示例中有一個循環...這必須是循環的目的。我在代碼示例中恢復了循環。您可能需要查看原始博客條目。你的網頁上真的有20個小文本編輯器嗎?這似乎很不尋常。 – 2009-08-08 22:24:09

+0

是的,用於編輯聯繫人詳細信息(姓名,電話等) – Alex 2009-08-08 22:26:05

1

下面是我通過反射做:

查看:

$(".edit").editable('<%=Url.Action("UpdateEventData","Event") %>', { 
       submitdata: {eventid: <%=Model.EventId %>}, 
       tooltip: "Click to edit....", 
       indicator: "Saving...", 
       submit : "Save", 
       cancel : "Cancel" 
      }); 

控制器:

public string UpdateEventData(int eventid, string id, string value) 
    { 
     //load the event 
     var evt = Repository.GetEvent(eventid); 

     //UpdateModel; 
     System.Reflection.PropertyInfo pi = evt.GetType().GetProperty(id); 
     if (pi==null) 
      return ""; 
     try 
     { 

      object newvalue = Concrete.HelperMethods.ChangeType(value, pi.PropertyType); 

      pi.SetValue(evt, newvalue, null); 
      Repository.Save(); 

     } 
     catch (Exception ex) 
     { 
      //handle errors here 
     } 

     return pi.GetValue(evt, null).ToString(); 

    } 

的方法「HelperMethods.ChangeType」是Convert.ChangeType(所以它可以處理nullables),我從http://aspalliance.com/author.aspx?uId=1026得到了一個更強大的版本。