【发布时间】:2017-03-01 18:24:36
【问题描述】:
是否可以使用 ajax 将我的视图模型传递给控制器,而无需“重建”对象?
我有我的看法:
@using Project.Models
@model InfoFormulaireEnqueteModele
@section Style{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />}
@section Scripts{
@Scripts.Render("~/bundles/autocomplete")
@Scripts.Render("~/bundles/timeentry")
<script type="text/javascript">
var $status = $('#status'),
$commentBox = $('#commentBox'),
timeoutId;
var model = @Model; //<- something's wrong here
$commentBox.keypress(function () {
$status.attr('class', 'pending').text('changes pending');
// If a timer was already started, clear it.
if (timeoutId) clearTimeout(timeoutId);
var r = '';
// Set timer that will save comment when it fires.
timeoutId = setTimeout(function () {
var test = $('#commentBox').val();
// Make ajax call to save data.
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: '/Enquete/IndexPartial/',
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
$status.attr('class', 'saved').text('changes saved');
}, 1000);
return r;
});
</script>
控制器:
[HttpPost]
public PartialViewResult IndexPartial(InfoFormulaireEnqueteModele m)
{
return PartialView("_IndexPartial", m);
}
我可以访问我的控制器,但我的模型 (m) 在控制器中只有一次空值。这些值在发送到视图之前在控制器中设置。
【问题讨论】:
-
当你发送到控制器时,你在哪里设置值。您需要设置 vales 然后使用 send back 。请注意你使用 post 所以你需要发送 json 值。 ig 你打印模型,如果我没有错,它将为空。
-
你能告诉在控制台打印这个 JSON.stringify(model)
-
你想在这里做什么?为什么要将原始未更改的模型传回服务器?
-
@StephenMuecke 我将其称为自动保存功能..仅在用户停止编辑字段 1 秒后才会调用它(目前它仅适用于#commentBox,但如果我能做到的话工作,我将把它应用到整个表格)。
-
@Model是服务器端代码 - 它是您最初发送给客户端的模型。要将其发回,您需要使用var model = @Html.Raw(Json.Encode(@Model));,但这毫无意义。如果您想要输入的值,那么它的data: { commentBox: $('#commentBox').val() }或包含所有表单控件 -data: $('form').serialize(),(并删除contentType选项)
标签: asp.net ajax asp.net-mvc