在我的 Controller 中,我将一个对象列表发送到 View 中 (index.cshtml
)
return View(AdsPrevModel);
在我的index.cshtml
中:
<div id ="ele">
<ul>
<li> name1<input id="a1" type="checkbox"/></li>
</ul>
</div>
当用户单击复选框时,我使用 jquery 来了解用户是否选中了该框:
我的 JavaScript 文件:
$('#ele :checkbox').click(function () {
if ($(this).is(':checked')) {
alert($(this).attr('id'));
} else {
alert('unchecked');
}
});
如何将 AdsPrevModel 放入我的 js 文件中?
我知道我可以做这样的事情:
在我的 html 中添加:
<input type="hidden" id="AdsPrevModel" value="@Model.AdsPrevModel" />
在js中:
var adsPrevModel = JSON.parse(document.getElementById('AdsPrevModel').value);
是否还有其他选项,无需在我的 html 中添加隐藏输入?
也许js文件中的内容如下:
var adsPrevModel = JSON.parse(Model.AdsPrevModel));
最佳答案
最佳实践是
对该 Controller 进行 ajax 调用,该 Controller 应返回 json 结果
return JSON( model ) ;
关于javascript - 将 Controller 返回的对象获取到 JavaScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19121431/