简体   繁体   中英

Window.Location.Href or other methods of redirecting _self not working (MVC View)

I'm sure there is probably a very simple explanation for this, but I have tried several methods to no avail.

A little new to MVC but I've set up a controller with a conditional search param and now just need a way of passing it the parameter via querystring.

Direcly navigating to:

Collectors/Index?searchName=Tom

works perfectly, so I've set up a Textbox on the view to accept the parameter and am trying to redirect user to searchName= Input.

The problem is that for some reason the window.location.href function is not redirecting the page at all. I've tried window.open method with target set to _self, and that didn't work - however using target _new or not specifying always works.

Is there any reason why the function wouldn't work on the same window?

The following produces an alert before, no redirect and no alert after:

        $("#search").click(function () {
        alert("before");
        window.location.href("../Collector/Index?collectorName=Tom");
        alert("after");

however this produces both alerts and the redirect (as well as search results)

  $("#search").click(function () {
        alert("before");
        window.open("../Collector/Index?collectorName=Tom");
        alert("after");
    });

My controller action:

public ActionResult Index(string collectorName)
    {

        var db = new CollectorsCRUDController();

        var query = db.GetEXCEL_Collectors();

        if (!String.IsNullOrEmpty(collectorName))
        {
            query = query.Where(c => c.CollectorName.Contains(collectorName));

        }


        return View(query);

    }

Any tips would be awesome! Thank you!

Resolved


For anyone else that's having a problem with this:

my problem was that I was using the wrong syntax to call the window.location method...

window.location = URL 

not

window.location(URL); 

the full code that worked for me

    $("#search").click(function () {
        var query = $("#searchName").val();
        window.location = "/Collector/Index?collectorName=" + query;
    });

Edited:

window.location / window.location.href and other variants require setting with the = operator, rather than with parentheses ( () ) such as used with window.open() .

Change: window.location.href("../Collector/Index?collectorName=Tom");

To: window.location.href="../Collector/Index?collectorName=Tom";

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