我正在尝试使用以下代码对我的 MVC 模型进行编码,但警报消息给了我一个空值。我不确定为什么它给我一个空值,因为这是一个创建表单。我正在尝试从中创建一个模型,我的 html 代码具有以下外观:
@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>
}
它返回 null 因为它is无效的。用户最终输入表单的数据在页面呈现时不可用(并且您调用Json.Encode(Model)
运行)。 JavaScript 之类的东西运行客户端,当所有 Razor 东西运行时服务器端在发送给客户之前。如果您想从表单中获取用户输入的数据以在 AJAX 调用中使用,那么您需要按照 @Sippy 的建议进行操作并通过 JavaScript 检索它:
$('form').serializeObject();
另外,如果您确实需要在渲染时对模型进行实际编码(可能与 Knockout 等一起使用),则无需将其设置为字符串,然后解析该字符串。只需将其设置为常规 JavaScript 对象即可。这就是 JSON 的全部内容:
var model = @Html.Raw(Json.Encode(Model));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)