Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.BeginForm() with only form Id is not generating correct action url

I only want to add the formId in the beginForm()

If i try using
Html.BeginForm(null, null, FormMethod.Post, new {@id="Id"})

then the Html generated is
<form action="/newquestion/payment/b9f88f80-f31f-4144-9066-55384c9f1cfc" ... >

i don't know how that action url is generated so i tried,
Html.BeginForm(new {@id="Id"})
but then the action url looks like this
<form action="/newquestion/payment/Id... >

In both the cases the action url is not what it should be and it is not hitting the post action of the controller.

like image 333
Amit Avatar asked Nov 26 '13 02:11

Amit


People also ask

What is difference between Html BeginForm and Ajax BeginForm?

BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

What is the use of HTML BeginForm in MVC?

BeginForm(HtmlHelper, String, String, Object, FormMethod, Object) Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method and includes the HTML attributes.

Can we use multiple BeginForm in MVC?

Thanks for your help ! Multiple form tags should work fine in MVC unless they are nested.


2 Answers

When you are trying to generate a route, such as with BeginForm, MVC will do its best to include things that you might need.

If you're at domain.com/Home/Index/b9f88f80-f31f-4144-9066-55384c9f1cfc and you use the code that you have provided than the form will be generated with the action, controller and route values as it finds them.

controller / action / id
/Home      / Index  / b9f88f80-f31f-4144-9066-55384c9f1cfc

One way to get around this is to force id to be nothing (such as an empty string).

Observe:

@using (Html.BeginForm(null, null, new { @id = string.Empty },
    FormMethod.Post, new { @id = "Id" }))
{

}

The new { @id = string.Empty } is an anonymous object that represents the route values.

like image 107
Rowan Freeman Avatar answered Nov 15 '22 05:11

Rowan Freeman


Change @id to id.

 @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "MyForm1" }))    
    {
        <input id="submit" type="submit" value="Search" />
    }
like image 42
Yousuf Avatar answered Nov 15 '22 03:11

Yousuf