neda Derakhshesh neda Derakhshesh - 2 months ago 13
ASP.NET (C#) Question

Asp.net MVC Form posting

I have form like this in my Contact_Us view

@model vidiaweb_com.Models.Contact_US
....
<div id="contactus">
<div class="container">
<form class="form-group col-md-8">
<div id="contactuspost">
<h3 class="txtformat">Contact Us</h3>
<p class="txtformat">
We are here to answer any questions you may have. Reach out to us and we will respond as soon as we can.
</p>
<p class="txtformat">
Even if there is something you have always wanted to experience and can't find it on combadi, let us know and we promise we'll do our best to find it for you and send you there.
</p>
<br />
<div class="form">
@using (Html.BeginForm("Create", "Contact_Us"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
....
</div>
}
</div>
</div>
</form>
</div>
</div>
....
@Html.Partial("_MainFooter")


and this is my Contact_UsController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Email,Phone,Message,Date")] Contact_US contact_US)
{
if (ModelState.IsValid)
{
db.Contact_US.Add(contact_US);
db.SaveChanges();
return RedirectToAction("Index","Home");
}
return RedirectToAction("Index", "Home");
}


but in view when I Fill the Form and then click on submit button , it doesn't call
Create
action in the
Contact_Us
Controller. something like this is in my url

http://localhost:50074/Contact_Us/Index?__RequestVerificationToken=nrlDXOQglmGEzSQMqOqxm8ol4GiKeLffHoQUnLmuwhlIGcSFQfBrQxhZA8EL39nPLmG1FJQK42X284v60l6oepOytsmHLgwDOJYOgfmYnFU1&Name=dg&Email=d%40d.com&Phone=SF&Date=&Message=SFD


and it redirect again into my Contact_Us index view.

I had another form in my project like this but that one works correctly. does anyone have any idea what would the problem may be? thanks

Answer

You have nested forms (the <form class="form-group col-md-8"> contains your @Html.BeginForm()) which is invalid html and not supported.

The url your seeing is because your browsers submits the outer most form. Since the default method for a form is a GET, and the default action is to submit to the method that generated it (in your case Index()) it is generating a query string value for each form control.

Remove the <form class="form-group col-md-8"> tag and its closing </form> tag and the form generated by Html.BeginForm() will be submitted to the Create() POST method.