从Javascript MVC控制器传递数据

Passing data from Javascript MVC controller

本文关键字:数据 控制器 Javascript MVC      更新时间:2023-09-26

我是jQuery和Charts的新手。这是我的剧本,它运行良好。它为我提供了用户选择的复选框的id。我在我的控制器中有一个Chart动作,它也工作得很好,但它使用我的所有值创建了一个图表。我想要它创建一个图表基于所选的值是在我的脚本。我不知道如何将选定的值传递给我的控制器。

var checkboxes = $("input[type='checkbox']");
$(function ()
{
    function getValueUsingClass() {
        /* declare an checkbox array */
        var chkArray = [];
        /* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
        $(".chk:checked").each(function () {
            chkArray.push($(this).val());
        });
        /* we join the array separated by the comma */
        var selected = chkArray.join(",") + ",";
        /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
        if (selected.length > 1)
        {
            alert("You have selected " + selected);
        }
         else
         {
            alert("Please check at least one of the checkbox");
         }        
    }
    $("#Charter").click(function () {
        getValueUsingClass();
    });
});

在使用return selected;填充变量后返回您想要的js函数中的数据,然后通过发布表单或使用ajax将其发送回来。

将数据绑定到View页面上的元素,例如:

<input name="foo" id="yourId" value="bar" />

然后修改它的值:

$('#foo').val(getValueUsingClass());

并通过将表单发送给控制器来传递模型。

如果你想异步发送数据到你的控制器,那么你可以看看Ajax。

您可以使用ajax在getValueUsingClass()中调用您的控制器方法。

它可能看起来像这样:

$.ajax({
    url: "/YourControllerName/Chart",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: { arr: chkArray }, 
    success: function () {
        // do things upon success
    },
    error: function () {
        alert("Error!");
    }
});

也就是说,提供您的控制器动作有一个名为arr的参数,因为一旦将chkArray传递给控制器,json将其映射到它。