Ajax回发:从Controller读取数据

时间:2019-06-28 06:07:10

标签: ajax asp.net-mvc razor

如何在ajax回发中从控制器读取数据?

我有剃刀表格

@using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
   ....
}

然后我在JavaScript中捕获了Submit操作:

<script type="text/javascript">
    $(document).ready(function () {

        $("#createDocumentForm").submit(
            function () {
                showWaitMode();
                $.ajax({
                    data: ("#createDocumentForm").serialize, 
                    success: (e) => {
                        console.log(e);
                    },
                    error: (errorResponse) => {
                        alert(errorResponse)
                    }
                })
                return false;
            }
        );
    });
</script>

在我的控制器中,我点击了以下方法:

public ActionResult CreateDocument(NotatFletModel model)
{
    var reuslt = new
    {
        Staus = true,
        GoDocumentId = model.ContactId.ToString(),
        ErrorMessage = model.DocumentKindId,
    };

    return Json(reuslt);
}

但是在我的Ajax成功函数中,我想从控制器获取数据。我希望它在我的参数e中,但不是

简而言之:我该如何做Ajax发布并读取从控制器发布回的数据

1 个答案:

答案 0 :(得分:1)

使用ajax签出Form Post代码

HTML:

@using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}

Jquery:

 $("#createDocumentForm").submit(
        function (e) {
            showWaitMode();
            e.preventDefault(); 
            var form = $(this);
            var url = form.attr('action');
            $.ajax({
                url: url,
                type: 'POST',
                data: form.serialize(), // serializes the form's elements.
                success: function (data) {
                    console.log(data); // show response 
                },
                error: (errorResponse) => {
                    alert(errorResponse)
                }
            })
            return false;
        }
    );

控制器:

 //You can Use FormCollection also to get data
 //public ActionResult CreateDocument(FormCollection fc) {
 [HttpPost]     
 public ActionResult CreateDocument(NotatFletModel model) {
 //your logic
 return Json(model, JsonRequestBehavior.AllowGet);
 }