When I use a form to call a method on a controller, I want the page to refresh and the url to reflect the passed ASP MVC variable

Using ASP MVC, I created a web page for localhost / Dinner / 100 to show the details of the dinner for lunch with ID = 100.

The page has a dropdown that shows Dinner 1, Dinner 2, etc. The user has to select the weekend (Dinner 2, ID = 102) from the form and press "Submit". The page should refresh to show URL: localhost / Dinner / 102 and show lunch details 2.

My code works except for the url. During this my url shows localhost / Dinner / 100 even though it correctly displays the details of Dinner 2 (ID = 102).

My controller method is pretty simple:

    public ActionResult Index(string id)
    {
        int Id = 0;
        if (!IsValidFacilityId(id) || !int.TryParse(id, out Id))
        {
            return Redirect("/");
        }

        return View(CreateViewModel(Id));
    }

      

Can you help me figure out how to make this all work?

ps I created my own route for the method:

routes.MapRoute(
            "DinnerDefault",                         // Route name
            "Dinner/{id}",                           // URL with parameters
            new { controller = "Dinner", action = "Index", id = "" }  // Parameter defaults
        );

      

+2


a source to share


2 answers


If you are using the ASP.NET MVC HtmlHelper BeginForm () method, be aware that dafult uses the POST method.

I think the easiest way is to do it with the RedirectToAction result.

View:



<body>
    <% Html.BeginForm("Select", "Home"); %>
            <select id="dinners" name="dinners">
                <option value="100">dinner 1</option>
                <option value="101">dinner 2</option>
                <option value="102">dinner 3</option>
            </select>
            <button type="submit"></button>
    <% Html.EndForm(); %>
</body>

      

Controller:

    public ActionResult Index(string id)
    {
        int Id = 0;
        if (!IsValidFacilityId(id) || !int.TryParse(id, out Id))
        {
        return Redirect("/");
        }

        return View(CreateViewModel(Id));

    }

    public ActionResult Select(string dinners)
    {
        return RedirectToAction("Index", "Home", new {id = dinners});
    }

      

+1


a source


Input fields in forms can only modify the request portion of the URL request and only if you are using the "get" method as the method.

The lunch ID is probably passed in as "post". This will be hidden in the headers of the http pages, but will exceed the values ​​in the visible url.

You can change url on form posts in Html.BeginForm, but not dynamically based on form input, unless you use javascript to change form action.



An easier task could be to return the result of a RedirectToAction from your controller:

return RedirectToAction("Index", new { id = 102 ]);

      

But you will need to make sure you only do this when requested.

0


a source







All Articles