2017-03-01 239 views
-1

オブジェクトを '再構築'せずに、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)は、コントローラに一度だけNULL値を持っています..値はビューに送信される前にコントローラに設定されていました。あなたのアクションメソッドのspeciyで

+0

あなたがコントローラに送るとき、ru設定値はどこに。あなたはvalesを設定し、send backを使う必要があります。あなたがjsonの値を送る必要があるので、投稿を使ってu rに注意してください。あなたが間違っていない場合、それはnullになります。 –

+0

JSON.stringify(model) –

+0

ここで何をしようとしていますか?なぜ元の変更されていないモデルをサーバーに戻したいのですか? –

答えて

0

[FromBody]

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

以下のようにあなたはこのようにそれを行う必要がありますが:

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

あなたのモデルはJSONに変換し

をJSためにそれを渡す方法です
関連する問題