Paritosh
Paritosh

Reputation: 4503

mvc maintain url parameters during post

I currently have a form setup on the following url:

http://localhost/mySite/inventory/create/26/1

this goes to an actionMethod

    [HttpGet]
    public ActionResult create(int exId, int secId)


    [HttpPost]
    public ActionResult create(MyModel model, int exId, int secId, FormCollection form)

the form submit and button look like:

@using (Html.BeginForm("create", "inventory", new { @exId= Model.ExId, @secId= Model.SecId}, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

and

                <div class="col-md-6">
                <input type="submit" class="btn blue" value="Search" name="Searchbtn" id="Searchbtn" />
            </div>

my question was is there anyway during the post to keep the url as: /create/26/1, right now when the post occurs the url is changed to:

http://localhost/mySite/inventory/create?exId=26&secId=1

is there anyway to keep it as how the get has it, /create/26/1?

Upvotes: 1

Views: 610

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

That's most likely a routing issue. MVC short-circuits routing. In other words, as soon as it finds something that will work, it uses that, even if there is perhaps a better route available. In your scenario here, it's finding that /inventory/create is a valid route, and since query string params are arbitrary, it's just sticking the rest of the route values there. It's hard to say without seeing your route config, but if the route you have for /inventory/create/{exId}/{secId} comes after whatever route catches just /inventory/create, you should move it before that. If you're using attribute routing, there's no inherent order or routes, so you'll have to use a route name to distinguish which one you actually want to use.

All that said, the easiest thing to do here is to simply not generate the URL. You're doing a postback, so you can just use an empty action. I think you're mostly having this issue because you're trying to pass htmlAttributes to Html.BeginForm, which then requires that you specify a bunch of extra stuff that's not necessary. In these situations I recommend just using a static <form> tag. You don't have to use Html.BeginForm and when you find yourself doing contortions like this, it's better to just not.

<form class="form-horizontal" role="form" action="" method="post">
    ...
</form>

Upvotes: 2

Related Questions