Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to pass my view Model to the controller, using ajax, without 'rebuilding' the object?

I have my view:

@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>

Controller:

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

I am able to reach my controller, but my model (m) has only null values once in the controller.. The values were set in the controller before being sent to the view.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your action method speciy [FromBody] as below

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...