asp.net MVC-AJAX模型到控制器 [英] asp.net MVC - AJAX model to controller

查看:77
本文介绍了asp.net MVC-AJAX模型到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用ajax将视图模型传递给控制器​​,而无需重建"对象?

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

我有看法:

@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)在控制器中只有一次空值.这些值是在控制器中设置的,然后才发送到视图.

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.

推荐答案

您应该这样做:

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

这就是将模型转换为json并将其传递给js的方式

That's how you convert your model to json and pass it to js

这篇关于asp.net MVC-AJAX模型到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆