如何将jQuery变量值传递给c# mvc?
我需要在后面的 mvc 代码中获取变量 btn 的值。
$('button').click(function () {
var btn = $(this).attr('id');
alert(btn);
$.ajax({
type: 'GET',
url: '@Url.Action("ActionName", "ControllerName")',
data: { id: btn },
success: function (result) {
// do something
}
});
});
根据变量值(提交按钮(或(预览按钮(,我的模型将在某些字段上进行"必需"验证。
在我的控制器中,我调用为
[HttpGet]
public ActionResult ActionName(string id)
{
var vm = id;
return View(vm);
}
虽然,控制器中的ActionResult不会被调用。
Jquery : alert(btn(; -- 正在调用。我可以看到带有 id 的警报窗口。但是,我无法在控制器中检索 id。
您需要将jQuery.ajax()
(或其缩写形式jQuery.get()
/jQuery.post()
(与GET
/POST
方法一起使用,并使用参数设置控制器操作以传递按钮 ID:
jQuery (inside $(document(.ready(((
$('button').click(function () {
var btn = $(this).attr('id');
var url = '@Url.Action("ActionName", "ControllerName")';
var data = { id: btn };
// if controller method marked as POST, you need to use '$.post()'
$.get(url, data, function (result) {
// do something
if (result.status == "success") {
window.location = '@Url.Action("AnotherAction", "AnotherController")';
}
});
});
控制器操作
[HttpGet]
public ActionResult ActionName(string id)
{
// do something
return Json(new { status = "success", buttonID = id }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult AnotherAction()
{
// do something
return View(model);
}
如果要将检索到的按钮 ID 从 AJAX 传递到其他操作方法,可以利用TempData
或Session
来执行此操作。
你用"fetch"这个词来描述你想做的事情是一个很好的巧合。
jQuery作为前端框架在浏览器中运行。这意味着它在客户端计算机上运行。您的 MVC-C# 代码位于服务器上。因此,如果要在这两台计算机之间发送数据,则需要使用 http 协议。
1. Ajax 和 REST:
使用 http 方法(post 或 put(的 ajax 调用将变量值作为 JSON 推送到后端的 REST api(路由(。 对于此选项,您可能需要查看javascript的fetch函数。
2.HTML表格
使用 html 表单,将变量值存储在一个输入元素中。表单提交也将对后端执行 http post(默认情况下(请求,并使用所有输入元素值作为 post 参数。
有很多方法可以完成您想要做的事情,但我会坚持使用您的代码示例。
因此,您需要做的是利用jquery中的.ajax调用将数据从视图发送到控制器。更多关于这里的信息:http://api.jquery.com/jquery.ajax/
使用您的代码,您将 .ajax 调用放在逻辑流中,根据单击哪个按钮来执行的操作。
$("button").click(function ()
{
var btn = this.id;
if (btn == "previewButton")
{
$.ajax({
url: "/MyApp/MyAction",
type: "POST",
data: { btnId: btn },
dataType: "json",
async: true,
cache: false
}).success(function(data){
// do something here to validate if your handling worked
}).error(function(){
// Do something here if it doesnt work
});
}
}
您会看到有一个网址。在我的示例中,我选择了 MyApp 作为我的控制器,并选择了 MyAction 作为我们要在其中发布值的控制器的方法。ajax 调用发布 1 个属性为 btnId 的参数。如果需要传递更多数据,jquery 调用中的属性名称应与控制器中 actions 方法签名的参数相对应。
所以我的控制器看起来像
public MyAppController : Controller
{
[HttpPost]
public JsonResult MyAction(string btnId)
{
Debug.WriteLine("btnId: {0}", btnId);
return Json(new{ ButtonId= btnId });
}
}
这将是使用 jquery 的 .ajax 调用处理将值从视图传递到控制器的一种方法。
我的首选方法是使用Ajax.BeginForm的Html助手,这可能是您的另一种选择。
https://www.aspsnippets.com/Articles/ASPNet-MVC-AjaxBeginForm-Tutorial-with-example.aspx