我目前正在嘗試使用修改的索引視圖創建設置頁面。目標是用戶獲得所有設置顯示,並可以更改所有設置在一個視圖和保存所有設置使用一個單一按鈕。該設置應該使用Ajax進行更新。如何更新列表<Model>與jQuery在MVC 4
我目前的做法:
查看:
<script language="javascript">
$(function() {
$('#editSettings').submit(function() {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
alert(result);
}
});
}
return false;
});
});
</script>
[ ... ]
@using (Ajax.BeginForm("Edit", "Settings", new AjaxOptions {UpdateTargetId = "result"}, new { @class = "form-horizontal", @id = "editSettings" }))
{
foreach (Setting item in ViewBag.Settings)
{
@Html.Partial("_SingleSetting", item)
}
<input type="submit" value="modify" />
}
局部視圖加載設置:
<div class="control-group">
<label class="control-label">@settingName</label>
<div class="controls">
@Html.EditorFor(model => model.Value)
<span class="help-inline">@settingDescription</span>
</div>
</div>
型號:
[Table("Settings")]
public class Setting
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SettingId { get; set; }
public string Name { get; set; }
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Value { get; set; }
}
我使用ViewBag.Settings = _db.Settings.ToList();
jQuery的解析數據,以以下的方法設置ViewBag:
[HttpPost]
public ActionResult Edit(IList<Setting> setting)
{
Console.WriteLine(setting.Count);
return Content(""); // Currently for testing purposes only. Breakpoint is set to setting.Count
}
Count
因爲設置是null
引發錯誤。我很不確定如何解決這個問題。
有人可以給我一個提示嗎?
This SO上的主題已經涵蓋了更新沒有Ajax的Collection。但我不明白這一點。
謝謝你的幫助。
非常感謝您的詳細解答。這給了我一個關於EditorTemplates的完整的新視圖*,以及與視圖結合使用的List <>。 – 2013-03-04 08:40:33