Search code examples
asp.net-mvcrazorurl-routing

Reload page but get a 404 error because of wrong url when routing in MVC


My View is called Survey.cshtml. My current url is http://localhost:17471/Campaign/Survey/6184.

In this page I have a drop down menu to select language. There are English and Spanish. One I select the language, I want to reload the page because some context are shown in different language. I still want to keep the same url.

My code in Survey.cshtml.

 $("#id").change(function () {
            var selectedValue = $(this).find('option:selected').text();
            window.location.href = "@Url.Action("Survey1", "Campaign", new {id=Model.SurveyModel.CampaignId, languageName = "languageToken" })".replace("languageToken", selectedValue);

        });

However it goes to the url http://localhost:17471/Campaign/Survey1/6184?languageName=Spanish

My controller CampaignController.cs has the methods.

    public ActionResult Survey(int id)
    {
       // omitted code
        return View(model);
    }

    [HttpPost]
    public ActionResult Survey1(int id, string languageName)
    {
        // omitted here
        var view = "Survey";
        return View(view,model);
    }

I don't have Route for the above methods in RouteConfig.cs. I am not very strong on MVC Routing. Sometimes I am confused the old-and-good HTTP URL ENCODING with the http://site-address/page.html?param1=value1&param2=value2 and the MVC ROUTING which uses the form of http://site-address/page/value1/value2.

So help me.


Solution

  • Your Survey1 action is decorated with [HttpPost], which means you have to use the POST method from your client. But when you do a redirect with window.location.href, that always uses the GET method. You have two options:

    1. Change your controller action and remove [HttpPost].
    2. Create a form with the POST method and your values in it, and use javascript to trigger the submit event on that form instead of using window.location.href.