asp.net MVC - AJAX模型到控制器

asp.net MVC - AJAX模型到控制器

问题描述:

是否有可能通过我的视图模型控制器,使用Ajax,没有'重建'的对象?asp.net MVC - 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)的控制器只有空值一次。该值被发送到视图之前在控制器中设置。

+0

当你发送给控制器时,ru设置值。你需要设置值,然后使用回送。请注意你使用post,所以你需要发送json值。 ig你打印模型,它会是空的,如果我没有错。 –

+0

你能告诉在控制台中打印这个JSON.stringify(model) –

+0

你在这里试图做什么?你为什么想要将原来不变的模型传回服务器? –

在你的操作方法speciy [FromBody]如下

[HttpPost] 
public PartialViewResult IndexPartial([FromBody] InfoFormulaireEnqueteModele m) 
{ 
    return PartialView("_IndexPartial", m); 
} 

你应该做的是这样的:

var model = @Html.Raw(Json.Encode(@Model)); 

这就是你如何转换你的模型JSON和它传递给js的