如何发送JS变量MVC控制器 [英] How to send js variables to mvc controller
问题描述
我真的新的客户端 - 服务器的编程概念。我需要什么,派遣4 JS瓦尔我的MVC 3控制器动作。
I`m new to client-server programming concepts. What I need, to send four js vars to my MVC 3 controller action.
$(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
};
}
});
所以我让我的VAR在浏览器中。
So i get my vars in browser.
我对服务器端的是:
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; }
}
有一个简单的方法来后我从JS 4 PARAMS我的行动?
我试图用几个例子,从这个网站上,使用$阿贾克斯
Is there an easy way to post my four params from js to my action? I tried to use couple examples from this site, using $.ajax
筛选
$.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
});
不过,这并不工作,我在行动收到0 0 0 0。但老实说,我真的甚至不知道如何调用该函数的jQuery。我应该把它通过点击按钮,或自动调用,当我张贴的形式?
以及是否有送其他的方法这PARAMS?
But it does not worked, i received 0 0 0 0 in my action. But honestly I`m not even sure how to call this jquery function. 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 -
示范 -
public class ImageCoordinates
{
public int x1 { get; set; }
public int x2 { get; set; }
public int y1 { get; set; }
public int y2 { get; set; }
}
动作 -
public ActionResult CreateCover(ImageCoordinates coordinates)
{
return null;
}
让我们创建一个视图这将使得AJAX调用动作。
Lets create a View which will make the AJAX call to the Action.
<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()" />
输出 -
这篇关于如何发送JS变量MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!