c# - 如何使用 EditorFor 保存对模型的更改?
问题描述
我有这样的看法:
@model IEnumerable<Namespace.MyClass>
@using Newtonsoft.Json;
<form asp-action="Update">
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Product)
</th>
<th>
@Html.DisplayNameFor(model => model.IsAvailable)
</th>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Product)
</td>
<td>
@Html.EditorFor(modelItem => item.IsAvailable)
</td>
</tr>
}
</tbody>
</table>
<div>
<a href=@Url.Action("SaveChanges", "Product", new {productList = JsonConvert.SerializeObject(Model) })> Save changes</a>
</div>
</form>
SaveChanges 看起来像这样:
[HttpGet] // Perhaps it should be HttpPost here, but if I change it to that nothing happens when I run the program after clicking the "Save changes" link
public ActionResult SaveChanges(string productList)
{
List<MyClass> products = JsonConvert.DeserializeObject<List<MyClass>>(productList);
// Here I continue with SqlCommand to later make an UPDATE to a database changing the value of IsAvailable which is the only adjustable value in my view
}
我的问题是,当我运行程序并将 IsAvailable (这是一个布尔值)从我的视图中更改false
为true
并按“保存更改”时,模型不会改变,即 productList 对于该特定产品的 IsAvailable 仍然具有值 False .
有人知道为什么吗?据我了解,如果我有一个和
解决方案
当您通过链接将模型发送到操作时,模型信息不会更新。并且发送相同的初始金额。
您对模型字段所做的更改仅在 html 控件中,与模型无关。当您发布表单信息时,模型会更新。
我在以下代码中将表单提交给 jQuery
在视野中
@model List<Namespace.MyClass>
@using (Html.BeginForm("SaveChanges", "Product", FormMethod.Post))
{
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Product)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().IsAvailable)
</th>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Model[i].Product)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].IsAvailable)
</td>
</tr>
}
</tbody>
</table>
<div>
@Html.ActionLink("Save changes", "", null, new { @id = "submit"})
</div>
}
@section scripts{
<script type="text/javascript">
$("#submit").click(function () {
document.forms[0].submit();
return false;
});
</script>
}
控制器中的动作
[HttpPost] // Perhaps it should be HttpPost here, but if I change it to that nothing happens when I run the program after clicking the "Save changes" link
public ActionResult SaveChanges(IEnumerable<MyClass> products)
{
// Here I continue with SqlCommand to later make an UPDATE to a database changing the value of IsAvailable which is the only adjustable value in my view
}
推荐阅读
- ruby - Redundant curly braces around a hash parameter for Rubocop in rails
- ios - 当我构建 ios 应用程序(cordova)
- azure - CosmosDb 中的日期差异
- c# - 我们可以使用后面的隐藏字段选项代码检索 DDL 的文本值吗?
- android - 在 Android Studio 3.x 和 CMake 中静态链接库
- sql - Retain values till there is a change in value in Teradata
- .htaccess - 当 url 不以 / 结尾时出现 .htaccess 错误
- c# - 错误:运算符“*”不能应用于“字符串”和“整数”类型的操作数。
- php - Display modal from another blade laravel
- html - 引导 btn 组不工作