, , , json. , .
. :
public class MyViewModel
{
public IDictionary<string, string> BookVars { get; set; }
}
:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{BookVars = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
The view contains a form and includes a custom script to represent ajax. Values can be saved and modified in any way. You can use hidden fields.
@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, creates a simple jquery plugin to represent ajax using serialization of your json data:
(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);
If you find this useful, you can also write your own json binder using, for example, the Newtonsoft.Json library.
You are done.
source
share