简体   繁体   English

如何将jQuery变量值传递给C#MVC?

[英]How to pass jQuery variable value to c# mvc?

How to pass jQuery variable value to c# mvc ? 如何将jQuery变量值传递给C#MVC?

I need to fetch the value of the variable btn in mvc code behind. 我需要在后面的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
            }
        });
    });

Based on the variable value (Submit Button (or) Preview Button), my model will have Required validation on certain fields. 基于变量值(“提交按钮”(或“预览”按钮),我的模型将在某些字段上具有“必填”验证。

In my controller , i am calling as 在我的控制器中,我称

[HttpGet]
    public ActionResult ActionName(string id)
    {

        var vm = id;
        return View(vm);
    }

Though , ActionResult in controller is not invoked. 不过,不会调用控制器中的ActionResult。

Jquery : alert(btn); jQuery的:alert(btn); -- is calling. -正在打电话。 I can see the alert window showing with the id. 我可以看到带有ID的警报窗口。 However, I am not able to retrieve the id in the controller. 但是,我无法在控制器中检索ID。

It is a nice coincidence that you use the word "fetch" to describe what you want to do. 您使用“提取”一词来描述您想要做的事是一个很好的巧合。

jQuery runs in the browser as a frontend framework. jQuery在浏览器中作为前端框架运行。 Meaning that it runs on the client`s computer. 这意味着它在客户端计算机上运行。 Your MVC-C#-Code lies on the server. 您的MVC-C#代码位于服务器上。 Therefore, if you want to send data between those two computers, you need to use the http protocol. 因此,如果要在这两台计算机之间发送数据,则需要使用http协议。

1. Ajax and REST: 1. Ajax和REST:

Using an ajax call using http methods (post or put) to push your variable value as JSON to the backend`s REST api (route). 使用使用http方法(发布或放置)的ajax调用将变量值作为JSON推送到后端的REST api(路由)。 For this option, you might want to have a look at the fetch function of javascript. 对于此选项,您可能想看看javascript的提取功能

2. HTML Forms 2. HTML表单

Use a html form where you store the variable value inside one input element. 使用html格式 ,将变量值存储在一个输入元素中。 A form submission will perform a http post (by default) request to the backend as well and use all input element values as post parameters. 表单提交也将对后端执行一个http post(默认)请求,并将所有输入元素值用作post参数。


If you down vote this answer, could you please provide feedback what I could do better. 如果您对此答案投反对票,请提供反馈,我可以做得更好。 That`s the only way I can learn form mistakes and improve. 那是我学习形式错误并改进的唯一方法。 Thanks. 谢谢。

You need to use jQuery.ajax() (or its shortened form jQuery.get() / jQuery.post() ) with GET / POST method and set up a controller action with an argument to pass button ID: 您需要将jQuery.ajax() (或其缩写形式jQuery.get() / jQuery.post() )与GET / POST方法一起使用,并设置带有参数的控制器操作以传递按钮ID:

jQuery (inside $(document).ready()) jQuery(在$(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")';
        }
    });
});

Controller action 控制器动作

[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);
}

If you want to pass retrieved button ID from AJAX into other action method, you can utilize TempData or Session to do that. 如果要将从AJAX检索到的按钮ID传递给其他操作方法,则可以使用TempDataSession来执行此操作。

There are many ways to accomplish what you are looking to do, but I'll stick to using your code sample. 有很多方法可以完成您想要的工作,但是我将坚持使用您的代码示例。

So what you need to do is utilize the .ajax call in jquery to send data from your view to your controller. 因此,您需要做的是利用jquery中的.ajax调用将数据从视图发送到控制器。 More on that here: http://api.jquery.com/jquery.ajax/ 此处的更多信息: http : //api.jquery.com/jquery.ajax/

Using your code, you'd put the .ajax call within your logic flow of what to do based on which button is clicked. 使用您的代码,您可以将.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
        });

    }

} }

You'll see that there is a URL. 您会看到有一个URL。 In my example i've chose MyApp as my controller and MyAction as the method of the controller in which we are posting values to. 在我的示例中,我选择MyApp作为我的控制器,选择MyAction作为我们向其中发布值的控制器的方法。 The ajax call posts 1 parameter with a property of btnId. ajax调用发布了一个具有btnId属性的参数。 If you need to pass more data, the property name in the jquery call should correspond with an argument of the actions method signature within the controller. 如果需要传递更多数据,则jquery调用中的属性名称应与控制器内的action方法签名的参数相对应。

So my controller looks like 所以我的控制器看起来像

public MyAppController : Controller 
{
    [HttpPost]
    public JsonResult MyAction(string btnId)
    {
        Debug.WriteLine("btnId: {0}", btnId);

        return Json(new{ ButtonId= btnId });
    }
}

This would be one way to handle passing values from your view to your controller using .ajax calls with jquery. 这将是通过使用带有jquery的.ajax调用来处理从视图向控制器传递值的一种方法。

My preferred way is to use the Html helpers of Ajax.BeginForm which could be another option for you. 我的首选方法是使用Ajax.BeginForm的HTML帮助器,这可能是您的另一选择。

https://www.aspsnippets.com/Articles/ASPNet-MVC-AjaxBeginForm-Tutorial-with-example.aspx https://www.aspsnippets.com/Articles/ASPNet-MVC-AjaxBeginForm-Tutorial-with-example.aspx

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

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