下面是我通過反射做:
查看:
$(".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得到了一個更強大的版本。
但是如果我有一個大型模型,比如有20個屬性會怎樣。我需要20種不同的控制器方法嗎?或者如果我使用了一個通用的id/value參數對,那麼我如何讓這個值自動更新正確的對象屬性? – Alex 2009-08-08 21:22:50
原始代碼示例中有一個循環...這必須是循環的目的。我在代碼示例中恢復了循環。您可能需要查看原始博客條目。你的網頁上真的有20個小文本編輯器嗎?這似乎很不尋常。 – 2009-08-08 22:24:09
是的,用於編輯聯繫人詳細信息(姓名,電話等) – Alex 2009-08-08 22:26:05