开发者

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

Using ASP MVC, I have set up a webpage for localhost/Dinner/100 to show the dinner details for dinner with ID = 100.

On the page, there is a dropdown that shows Dinner 1, Dinner 2, etc. The user should select the dinner of interest (Dinner 2, ID = 102) off the form and press submit. The page should refresh and show the url: localhost/Dinner/102, and show the details of dinner 2.

My code is working except for the url. During this, my url shows localhost/Dinner/100 even though it is correctly displaying 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 get this all working?

p.s. I did create a custom route for the method:

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


If you are using ASP.NET MVC HtmlHelper BeginForm() method, keep in mind that by dafult it uses the POST method.

I Think the easiest way is to do this via 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});
    }


Input fields in forms can only change the querystring portion of a URL and only if you use 'get' as the method.

The dinner id is probably being passed as a 'post' value. This will be hidden in the page's http headers, but will over right the values in the visible url.

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

An easier thing to do might be to return a RedirectToAction result from your controller:

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

But you'd need to make sure you only did this on post requests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜