简体   繁体   中英

How to pass jQuery variable value to c# mvc?

How to pass jQuery variable value to c# mvc ?

I need to fetch the value of the variable btn in mvc code behind.

$('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.

Jquery : alert(btn); -- is calling. I can see the alert window showing with the id. However, I am not able to retrieve the id in the controller.

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. Meaning that it runs on the client`s computer. Your MVC-C#-Code lies on the server. Therefore, if you want to send data between those two computers, you need to use the http protocol.

1. Ajax and 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). For this option, you might want to have a look at the fetch function of javascript.

2. HTML Forms

Use a html form where you store the variable value inside one input element. 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.


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 (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")';
        }
    });
});

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.

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. More on that here: 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.

$("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. 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. The ajax call posts 1 parameter with a property of 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.

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.

My preferred way is to use the Html helpers of Ajax.BeginForm which could be another option for you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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