gpt4 book ai didi

jquery - 如何在 MVC 4 中使用 jQuery 更新 List

转载 作者:行者123 更新时间:2023-12-01 00:37:58 25 4
gpt4 key购买 nike

我目前正在尝试使用修改后的索引 View 创 build 置页面。目标是用户可以显示所有设置,并且可以在一个 View 中更改所有设置,并使用一个按钮保存所有设置。应使用 Ajax 更新设置。

我目前的方法:

查看:

<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" />
}

加载设置的部分 View :

        <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();设置ViewBag

jQuery 将数据解析为以下方法:

    [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 更新集合。但我不会明白这一点。

感谢您的帮助。

最佳答案

您正在使用 Ajax.BeginForm 并使用 jQuery 再次对表单进行 ajax 化。那没有必要。但代码的真正问题是部分中输入字段的名称。您没有尊重naming convention由默认模型绑定(bind)器用于绑定(bind)到列表。

让我们看一个完整的示例(为了简单起见,删除所有噪音,例如 Entity Framework ):

型号:

public class Setting
{
public int SettingId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}

Controller :

public class SettingsController : Controller
{
public ActionResult Index()
{
// No idea why you are using ViewBag instead of view model
// but I am really sick of repeating this so will leave it just that way
ViewBag.Settings = Enumerable.Range(1, 5).Select(x => new Setting
{
SettingId = x,
Name = "setting " + x,
Value = "value " + x
}).ToList();
return View();
}

[HttpPost]
public ActionResult Edit(IList<Setting> setting)
{
// Currently for testing purposes only. Breakpoint is set to setting.Count
return Content(setting.Count.ToString());
}
}

查看(~/Views/Settings/Index.cshtml):

@using (Html.BeginForm("Edit", "Settings", FormMethod.Post, new { @class = "form-horizontal", id = "editSettings" }))
{
foreach (Setting item in ViewBag.Settings)
{
@Html.Partial("_SingleSetting", item)
}
<input type="submit" value="modify" />
}

@section scripts {
<script type="text/javascript">
$('#editSettings').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert(result);
}
});
}
return false;
});
</script>
}

设置部分(~/Views/Settings/_SingleSetting.cshtml):

@model Setting
@{
var index = Guid.NewGuid().ToString();
ViewData.TemplateInfo.HtmlFieldPrefix = "[" + index + "]";
}

<input type="hidden" name="index" value="@index" />

<div class="control-group">
<label class="control-label">@Html.LabelFor(x => x.Name)</label>
<div class="controls">
@Html.EditorFor(model => model.Value)
</div>
</div>

请注意在部分内部如何需要更改 HtmlFieldPrefix,以便 html 帮助程序为您的输入字段生成正确的名称并遵守命名约定。

<小时/>

好吧,现在让我们删除 ViewCrap 并正确执行操作(当然,即使用 View 模型)。

一如既往,我们从编写 View 模型开始:

public class MyViewModel
{
public IList<Setting> Settings { get; set; }
}

然后我们调整 Controller :

public class SettingsController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();

// you will probably wanna call your database here to
// retrieve those values, but for the purpose of my example that
// should be fine
model.Settings = Enumerable.Range(1, 5).Select(x => new Setting
{
SettingId = x,
Name = "setting " + x,
Value = "value " + x
}).ToList();
return View(model);
}

[HttpPost]
public ActionResult Edit(IList<Setting> setting)
{
// Currently for testing purposes only. Breakpoint is set to setting.Count
return Content(setting.Count.ToString());
}
}

查看(~/Views/Settings/Index.cshtml):

@model MyViewModel

@using (Html.BeginForm("Edit", "Settings", FormMethod.Post, new { @class = "form-horizontal", id = "editSettings" }))
{
@Html.EditorFor(x => x.Settings)
<input type="submit" value="modify" />
}

@section scripts {
<script type="text/javascript">
$('#editSettings').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert(result);
}
});
}
return false;
});
</script>
}

设置模型的编辑器模板 (~/Views/Settings/EditorTemplates/Settings.cshtml):

@model Setting
<div class="control-group">
<label class="control-label">@Html.LabelFor(x => x.Name)</label>
<div class="controls">
@Html.EditorFor(model => model.Value)
</div>
</div>

现在一切都按惯例进行。无需编写任何 foreach 循环。 Index View 中的 @Html.EditorFor(x => x.Settings) 调用会分析 View 模型的 Settings 属性,并检测到它是某个其他模型的集合 (Setting 在这种情况下)。因此,它将开始循环遍历此集合并搜索相应的编辑器模板 (~/Views/Settings/EditorTemplates/Setting.cshtml),该模板将自动为此集合的每个元素呈现。因此,您甚至不需要在 View 中编写任何循环。除了简化代码之外,现在编辑器模板中的 Html.EditorFor(x => x.Value) 将为输入字段生成正确的名称。

关于jquery - 如何在 MVC 4 中使用 jQuery 更新 List<Model>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com