1

How can i combine razor and java script

I want to do this :

                @{Session["type"] = $(this).attr("id");}

I do that, but i got an error.

I've tried this but it's not work for me.

using javascript variable in MVC3 Razor view engine

And here is my code:

                $(document).on("click", ".btn-group", function() {
                var t = $(this).attr("id");

                var text = "@{Session["type"] = "JSVar";}";
                text = text.replace("JSVar", t);
            });

Can any one give me suggestion?

5
  • 2
    Session is server side. Javascript is client side. If you want to set the value of session property, then you need to send the data to the server. Commented Aug 18, 2016 at 10:05
  • i know that , with query string ,but i can do that because my action cant get new parameters (some reason) Commented Aug 18, 2016 at 10:09
  • there is any way to send data to server without post data (form or action link) Commented Aug 18, 2016 at 10:24
  • you cant set server side variables from client side Commented Aug 18, 2016 at 10:47
  • @user3726322 any update on this ? Commented Aug 30, 2016 at 13:01

1 Answer 1

0

You can't. In this case, you need to do it in the controller. Also, isn't a good practice to change Session values in the view. Try something like this:

public ActionResult ChangeType(int type) {
    Session["type"] = type;
}

In your javascript:

$(document).on("click", ".btn-group", function() {
    $.ajax({
        url: "@Url.Action("ChangeType")",
        data: { type: $(this).attr("id") },
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.