Hardik Gondalia
Hardik Gondalia

Reputation: 3717

How to redirect to another page in Jquery using Razor syntax

 $(".category-sub-opition-list li").click(function () {
        var id = $(this).attr("id");
        var category = getUrlParameter('category');
        @{
            var category = Request.QueryString["category"];
            var cat = Model.Items.Where(i => i.Id.ToString() == category).FirstOrDefault();
            if(cat==null)
            {
                Code to Redirec to page
            }
        }
    });

in JQuery I want to check Model list, whether the option is available in List or not, If category does not exists in list, I want to redirect page.

Upvotes: 0

Views: 786

Answers (1)

Neville Nazerane
Neville Nazerane

Reputation: 7059

I don't recommend writing razor inside js in this way with so may blocks. Create a separate function

    @{
        var category = Request.QueryString["category"];
        var cat = Model.Items.Where(i => i.Id.ToString() == category).FirstOrDefault();
        if(cat==null)
        {
            <script>
                function redirectIfNeeded(){
                    window.location = "@Url.Action()";   
                   // yes here using razor should be fine since it is just a line. 
                   //You can also hard code the url. 
                }
            </script>
        }
    }

You can now call your js function under var category = getUrlParameter('category'); without the razor code.

Upvotes: 1

Related Questions