我是客户端服务器编程概念的新手。我需要将四个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
};
}
});
因此,我在浏览器中获取了我的var。
我在服务器端拥有的是:
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发布到动作中?我尝试使用$ .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函数。我应该通过单击按钮来调用它,还是在发布表单时它自动调用?还有其他发送此参数的方法吗?
解决方案-
型号-
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;
}
让我们创建一个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()" />
输出-
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句