@{
ViewBag.Title = "Details";
}
@{
var data = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}
@section scripts
{
<script src="~/lib/knockout/dist/knockout.js"></script>
<script src="~/lib/knockout-mapping/knockout.mapping.js"></script>
<script src="~/js/realtyvm.js"></script>
<script type="text/javascript">
$(function () {
var realtyViewModel = new RealtyViewModel(@Html.Raw(data));
ko.applyBindings(realtyViewModel);
});
</script>
}
/* Realty Client ViewModel */
(function () {
RealtyViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/App/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.realtyViewModel != null)
ko.mapping.fromJS(data.realtyViewModel, {}, self);
}
});
}
}
})();
这看起来如何看待控制器动作:
public ActionResult Create()
{
RealtyViewModel realtyViewModel = new RealtyViewModel();
return View(realtyViewModel);
}
public JsonResult Save(RealtyViewModel realtyViewModel)
{
Realty realty = new Realty();
realty.Title = realtyViewModel.Title;
realty.Description = realtyViewModel.Description;
realty.RealtyType = realtyViewModel.RealtyType;
_repository.InsertRealty(realty);
_repository.Save();
realtyViewModel.MessageToClient = string.Format("{0} realty has been added to the database.", realty.Title);
return Json(new { realtyViewModel });
}
更新,我打开了XHR请求,详情如下:
请求有效负载
{Id: 0, Title: "Te", Description: "te", RealtyType: "te", MessageToClient: null}
Description:"te" Id:0 MessageToClient:null RealtyType:"te" Title:"Te"
响应:
{"realtyViewModel":{"id":0,"title":null,"description":null,"realtyType":null,"messageToClient":" realty has been added to the database."}}
答案 0 :(得分:0)
我已经解决了这个问题,方法是通过将[FromBody]添加到后期操作来指定即将发布的数据。
public JsonResult Save([FromBody]RealtyViewModel realtyViewModel)
{
Realty realty = new Realty();
realty.Title = realtyViewModel.Title;
realty.Description = realtyViewModel.Description;
realty.RealtyType = realtyViewModel.RealtyType;
_repository.InsertRealty(realty);
_repository.Save();
return Json(new { realtyViewModel });
}