0

I have go this code inside my razor view in Asp.Net:

@section MyScripts {
  <script type="text/javascript">
    $("button").click(function () {

        var myVariable = this.id;

        @{ 
            var Line1 = "Software";
            var Gruppe2 = Model.Where(x => x.Line1 == "Software").GroupBy(v => v.Line2).ToList();
        }
    });
  </script>
}

As you can see, the myVariable receives the id via jQuery from the "button click event".

So lets say that the variable value is "Software".

How can I pass this variable to the c# code inside the jQuery?

3
  • 1
    You need to understand the difference between client-side code and server-side code. You're looking for AJAX. Commented May 1, 2017 at 21:46
  • Thanks for your answer. So how would that work? I would send the variable via AJAX to my controller and give back a new view? The problem is I don't want to reload the whole view... @SLaks Commented May 1, 2017 at 21:50
  • 1
    You need to use AJAX and get back a JSON value. Commented May 1, 2017 at 21:54

1 Answer 1

1

Add an Ajax call to your click event that does a POST/GET back to your MVC action, something like this:

                $.ajax({
                    async: false,
                    cache: false,
                    url: '@Url.Action("MyAction", "MyController")',
                    type: 'GET',
                    dataType: 'json',
                    data: myJsonString }
);

Your action would only return json (or a partial view, depending on the return type)

    [HttpGet]
    public JsonResult MyAction()
    {

        string result = [some model data]

        var json = Json(result, JsonRequestBehavior.AllowGet);
        return json;

    }
Sign up to request clarification or add additional context in comments.

4 Comments

But then I have to reload my whole site or?
Ah okay I get it now. I will try it tomorrow and give you feedback if it worked!! Thanks a lot
No, usually you want to get back a json string and then use jQuery to change your UI. Like, for example, pass a state ID, get the State Description, and add that to a drop-down client-side.
Don't use async: false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.