[英]Pass a dictionary as a parameter in Http.Post in C#
我正在嘗試將字典傳遞給Html.Post中的動作方法
Html.BeginForm("ProcessStage2", "Supplier", new {bookVars = Model.BookVars} , FormMethod.Post, new { name = "frmBook" })
我可以傳遞模型的其他屬性(int,string,...)但不能傳遞Dictionary。 有沒有機會實現這一目標? 因為這本詞典有29對,它們似乎太多了,無法拆分並將它們分開傳遞。
您可以使用隱藏字段和編輯器模板。 我們來舉個例子:
模型:
public class MyViewModel
{
public IDictionary<string, string> BookVars { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// fill the dictionary with some dummy data
BookVars = Enumerable
.Range(1, 5)
.ToDictionary(x => "key" + x, x => "value" + x)
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model.BookVars property will be properly bound here
return View(model);
}
}
查看( ~/Views/Home/Index.cshtml
):
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.BookVars)
<button type="submit">OK</button>
}
編輯模板(〜/ Views / Home / EditorTemplates / KeyValuePair`2.cshtml):
@model KeyValuePair<string, string>
@Html.Hidden("Key", Model.Key)
@Html.Hidden("Value", Model.Value)
注意編輯器模板的名稱,它將自動為字典的每個元素呈現:KeyValuePair`2.cshtml
抱歉,我不能使用SO的編輯器來正確格式化,但文件的名稱應該是: KeyValuePair[grave accent]2.cshtml
其中[grave accent]
是嚴重的重音字符 。
另外,請不要忘記閱讀有關集合和字典的有線格式 ,默認模型綁定器希望更好地了解封面下發生的情況。
序列化您的字典並將其作為字符串傳遞(可能是base64編碼)。
不,您不能將對象作為參數傳遞。 唯一的方法是在數據庫中存儲對象,並傳遞該對象的POST only id。 您應該創建包含該Dictionary的模型:
public int id {get;set;}
public Dictionary<string, int> Dictionary {get;set};
並從服務器端通過id加載它。
你可以使用例如json序列化來做到這一點。 我推薦這個,因為它非常靈活,看起來很優雅。
您的模型可以包含任何對象集。 在你的情況下它是:
public class MyViewModel
{
public IDictionary<string, string> BookVars { get; set; }
}
在控制器中,您可以根據我們的需求存儲一些數據:
public class HomeController : Controller
{
public ActionResult Index()
{
// mock data
var model = new MyViewModel
{BookVars = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the binded model is avaliable
return View(model);
}
}
該視圖包含一個表單,並包含一個用於ajax提交的自定義腳本。 可以以任何方式持久化和修改這些值。 您可以使用例如隱藏字段。
@model MyViewModel
<script src="/Scripts/script.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('form').frmBookSubmit();
});
</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { name = "frmBook" }))
{
<div class="books">
@foreach (var item in Model.BookVars)
{
<input type="hidden" key="@item.Key" value="@item.Value" />
}
</div>
<input type="submit" />
}
Script.js,使用json序列化數據為ajax提交創建一個簡單的jquery插件:
(function ($) {
$.fn.frmBookSubmit = function () {
var $this = $(this);
if ($this != null && $this != 'undefined' && $this.length > 0) {
$this.submit(function (e) {
e.preventDefault();
var myviewmodel = new Object();
myviewmodel.BookVars = $this.find(".books").booksCollect();
var data = { model: myviewmodel };
var jsonString = JSON.stringify(data);
$.ajax({
url: $this.attr("action"),
type: 'POST',
dataType: 'json',
data: jsonString,
contentType: 'application/json; charset=utf-8'
});
});
}
};
$.fn.booksCollect = function () {
var books = new Array();
$(this).find("input").each(function () {
var k = $(this).attr('key');
var v = $(this).attr('value');
var item = {
Key: k,
Value: v
};
books.push(item);
});
return books;
};
})(jQuery);
如果您發現它很有用,您還可以使用例如Newtonsoft.Json庫編寫自定義json綁定器。
你完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.