gpt4 book ai didi

asp.net-mvc - 如何为 ASP.NET MVC 上的 GET 和 POST 操作绑定(bind)字典类型参数

转载 作者:行者123 更新时间:2023-12-04 20:03:15 24 4
gpt4 key购买 nike

我想定义一个显示标签和复选框列表的 View ,用户可以更改复选框,然后回发。我在发回字典时遇到问题。即post方法的字典参数为null。

以下是 GET 和 POST 操作的操作方法:

 public ActionResult MasterEdit(int id)
{

Dictionary<string, bool> kv = new Dictionary<string, bool>()
{
{"A", true},
{"B", false}
};

return View(kv);
}


[HttpPost]
public ActionResult MasterEdit(Dictionary<string, bool> kv)
{
return RedirectToAction("MasterEdit", new { id = 1 });
}

下面是景色

@model System.Collections.Generic.Dictionary<string, bool>
@{
ViewBag.Title = "Edit";
}
<h2>
MasterEdit</h2>

@using (Html.BeginForm())
{

<table>
@foreach(var dic in Model)
{
<tr>
@dic.Key <input type="checkbox" name="kv" value="@dic.Value" />
</tr>


}
</table>


<input type="submit" value="Save" />
}

任何想法将不胜感激!

最佳答案

不要为此使用字典。它们在模型绑定(bind)方面表现不佳。可能是 PITA。

View 模型会更合适:

public class MyViewModel
{
public string Id { get; set; }
public bool Checked { get; set; }
}

然后是一个 Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = "A", Checked = true },
new MyViewModel { Id = "B", Checked = false },
};
return View(model);
}

[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
return View(model);
}
}

然后是相应的 View (~/Views/Home/Index.cshtml):

@model IEnumerable<MyViewModel>

@using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
<input type="submit" value="Save" />
}

最后是相应的编辑器模板(~/Views/Home/EditorTemplates/MyViewModel.cshtml):

@model MyViewModel
<tr>
<td>
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.Checked)
@Html.DisplayFor(x => x.Id)
</td>
</tr>

关于asp.net-mvc - 如何为 ASP.NET MVC 上的 GET 和 POST 操作绑定(bind)字典类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858061/

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