简体   繁体   English

如何将js变量发送到mvc控制器

[英]How to send js variables to mvc controller

I`m new to client-server programming concepts.我是客户端-服务器编程概念的新手。 What I need, to send four js vars to my MVC 3 controller action.我需要什么,将四个 js 变量发送到我的 MVC 3 控制器操作。

    $(document).ready(function() {
        var $jcrop;

        $('#image').Jcrop({
            bgColor: 'red',
            onSelect: refreshData
        }, function () {
            $jcrop = this;
        });

        function refreshData(selected) {
            myData = {
                x1: selected.x1,
                x2: selected.x2,
                y1: selected.y1,
                y2: selected.y2
            };
        }
    });

So i get my vars in browser.所以我在浏览器中得到了我的变量。

What I have on server side is:我在服务器端拥有的是:

    public ActionResult CreateCover(ImageCoordinates coordinates) {
        ViewData.Model = coordinates;
        return View();
    }

public class ImageCoordinates
{
    public int x1 { get; set; }
    public int x2 { get; set; }
    public int y1 { get; set; }
    public int y2 { get; set; }
}

Is there an easy way to post my four params from js to my action?有没有一种简单的方法可以将我的四个参数从 js 发布到我的操作中? I tried to use couple examples from this site, using $.ajax我尝试使用此站点中的几个示例,使用 $.ajax

Like this像这样

        $.ajax({
            url: '/dashboard/createcover',
            type: 'POST',
            data: JSON.stringify(myData),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data.success);
            },
            error: function () {
                alert("error");
            },
            async: false
        });

But it does not worked, i received 0 0 0 0 in my action.但它不起作用,我在我的行动中收到了 0 0 0 0。 But honestly I`m not even sure how to call this jquery function.但老实说,我什至不确定如何调用这个 jquery 函数。 Should i call it by clicking the button, or it auto calls when i post the form?我应该通过单击按钮来调用它,还是在我发布表单时它会自动调用? And are there other methods to send this params?还有其他方法可以发送这个参数吗?

Here goes solution - 解决方法在这里-

Model - 型号-

public class ImageCoordinates
{
    public int x1 { get; set; }
    public int x2 { get; set; }
    public int y1 { get; set; }
    public int y2 { get; set; }
}

Action - 动作-

    public ActionResult CreateCover(ImageCoordinates coordinates)
    {
        return null;
    }

Lets create a View which will make the AJAX call to the Action. 让我们创建一个View,它将对Action进行AJAX调用。

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script>
    function submitForm() {

        var model = new Object();
        model.x1 = 120;
        model.y1 = 240;
        model.x2 = 360;
        model.y2 = 480;


        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("CreateCover")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ coordinates: model }),
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()" />

Output - 输出-

在此处输入图片说明

Try changing the name of the object passed to the controller: 尝试更改传递给控制器​​的对象的名称:

$.ajax({
    url: '/dashboard/createcover',
    type: 'POST',
    data: {coordinates : JSON.stringify(myData)}, //change here
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    },
    async: false
});

Please note that this will post the values as a JSON object. 请注意,这会将值作为JSON对象发布。 You need to modify your controller like so: 您需要像这样修改控制器:

public ActionResult CreateCover(string jsonCoordinates) {
    ImageCoordinates coordinates = JsonConvert.DeserializeObject<ImageCoordinates >(jsonCoordinates);

    ViewData.Model = coordinates;
    return View();
}

You also need to add a reference to Newtonsoft.Json . 您还需要添加对Newtonsoft.Json的引用。

In the situation that you don't want to use AJAX or want a quick work around you can also try adding a hidden field and then using Javascript(JS) to populate the value in that hidden field.在您不想使用 AJAX 或想要快速解决的情况下,您还可以尝试添加一个隐藏字段,然后使用 Javascript(JS) 填充该隐藏字段中的值。

    @Html.HiddenFor(m=>Model.ImageCoordinates.x1)
    <button type="submit">Submit Coordinates</button>

This will generate an 'input' tag on the html side with an id ="ImageCoordinates_x1" Then using JS这将在 html 端生成一个 id ="ImageCoordinates_x1" 的“输入”标签,然后使用 JS

function refreshData(selected) {
            myData = {
                x1: selected.x1,
                x2: selected.x2,
                y1: selected.y1,
                y2: selected.y2
            };
            return myData;
           
}

let coordinateData = refreshData(selected)
let x1 = document.getElementById("ImageCoordinates_x1");
x1.value = myData.x1;

You are now able to send the x1 coordinate information to the server through this.您现在可以通过此将 x1 坐标信息发送到服务器。 To send data to the other coordinates you will have to create hidden forms for them and populate the value of the input tag using JS要将数据发送到其他坐标,您必须为它们创建隐藏表单并使用 JS 填充输入标签的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM