I am currently trying to create a settings page using a modified Index view. The goal is that the users get all settings displayed and can change all settings within one view and save all settings using one single button. The setting should be updated using Ajax.
My current approach:
View:
<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" />
}
Partial View to load the setting:
<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>
Model:
[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; }
}
I am setting the ViewBag using ViewBag.Settings = _db.Settings.ToList();
The jQuery parses the Data to the following method:
[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 throws an error because setting is null. I am quite unsure how to fix this problem.
Can someone can give me a hint?
This topic on SO already covers updating a Collection without Ajax. But I won't get the point.
Thank you for your help.