如何正确使用Html.Raw(Json.Encode(Model))? [英] How to use Html.Raw(Json.Encode(Model)) properly?
问题描述
我正在尝试使用以下代码对MVC模型进行编码,但警报消息为我提供了一个空值.我不确定为什么给我一个空值,因为这是一个创建表单.我正在尝试从中创建一个模型,并且我的html代码具有以下外观:
I'm trying to Encode my MVC Model with the following code but the alert message gives me a null value. I'm not sure why it's giving me a null value because this is a create form. I'm trying to create a model from this and my html Code has the following look:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Customer</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="submit" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () {
var JsonModel = '@Html.Raw(Json.Encode(@Model))';
alert(JsonModel); // json as string
var model = JSON.parse(JsonModel); // will give json
alert(model);
$.ajax({
type: "POST",
url: "../Home/Index",
data: {"cus" : model},
success: function(data){
alert("done");
},
error:function(){
alert("Error!!!!");
}
});
});
});
</script>
}
推荐答案
My answer here shows (in the JQuery section) how you can get around using Json.Encode
altogether.
其背后的基本思想是,通过使用jQuery函数,您可以构建一个JSON对象,MVC可以将其解析为任何形式的数据模型.
The basic idea behind it is that by using a jQuery function you can build a JSON object, one that MVC will be able to parse into a data model, out of any form.
功能如下:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
在您的情况下,您的AJAX将变为
In your case, your AJAX would become
$.ajax({
type: "POST",
url: "../Home/Index",
data: { cus : JSON.stringify($('form').serializeObject()) },
success: function(data){
alert("done");
},
error:function(){
alert("Error!!!!");
}
});
如果$('form')
无法正常工作,或者同一页上有许多表格,则可以使用类或ID来唯一标识您的表格.
If you have trouble getting $('form')
working, possibly if you have numerous forms on the same page, use classes or IDs to uniquely identify your forms.
这篇关于如何正确使用Html.Raw(Json.Encode(Model))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!