将js数组传递给mvc控制器,然后返回另一个视图 [英] Pass js array to mvc controller, and then return another view

查看:63
本文介绍了将js数组传递给mvc控制器,然后返回另一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过发布将js数组从View传递到控制器,然后处理数据并将数据返回到另一个视图.

I want to pass js array from View via post to controller, then process the data and return the data to another view.

我遇到的问题:

-无法使用Ajax发布数据,因为我将无法返回其他视图

-can't use ajax to post data, because I won't be able to return another view

当您使用$ .post时,它会调用您的操作,然后返回一堆HTML.然后您什么也不做,因此浏览器将其抛出离开.如果您只想转到新页面,请定期发布并不要使用ajax.如果您需要调用服务器,则Ajax更适合获取一些信息来更新当前页面,而不是转到新页面.

When you use $.post it calls your action then gets back a bunch of HTML. And then you do nothing with it, so the browser just throws it away. If you want to just go to the new page, do a regular post and don't use ajax. Ajax is more for if you need to call your server to get some information to UPDATE the current page, not go to a new one.

(我想$ http.post也一样吗?)

(i guess it's the same for $http.post as well?)

-无法使用常规帖子(@ Html.Beginform),我认为是因为我将无法传递js数组?

-can't use regular post (@Html.Beginform) I think becaue I won't be able to pass the js array?

我应该如何处理?

推荐答案

如果您绝对想对js变量中的数据进行正常形式的commit( non-ajax ),则可以构建一些表单变量中的数据的输入元素,然后可以使用javascript提交此表单.只要元素名称与您的action方法参数匹配,模型绑定就可以工作.

If you absolutely want to do a normal form submit(non-ajax) with data in your js variable, you may build some form input elements for the data you have in your js variable and then you can use javascript to submit this form. As long as the name of the elements match with your action method parameter, model binding will work.

这是一个使用jQuery在按钮单击事件上发送字符串列表的简单示例.

Here is a simple example to send a list of strings on a button click event, using jQuery.

$(function() {

    var flags = ["aa", "bb", "cc"];
    var targetUrl="@Url.Action("Summary","Home")";

    $("#SubmitButton").click(function(e) {

        //First build a form element and set the action attribute value
        var $f = $("<form></form>").attr("action",targetUrl).attr("method","post");

        //Loop throug the string and create an input element for each item
        $.each(flags, function(a, b) {

            var $el = $("<input type='hidden' name='flagsChecked' />").attr("value",b);

            //Add the input element to the form
            $f.append($el);

        });

        //Add the form to the page and submit the form
        $f.appendTo("body").submit();

    });

});

,并且在您的http post操作方法中,您可以返回视图.

and in your http post action method , you can return a view.

[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
    return View("Summary");
}

如果您的代码要添加一些数据,我强烈建议您遵循

If your code is to udpate some data, i strongly suggest you to follow the P-R-G pattern and return a redirect response.

[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
    return RedirectToAction("Summary");
}

这篇关于将js数组传递给mvc控制器,然后返回另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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