HTML.BeginForm sends Post always to index action - asp.net-mvc

I'm trying to post a form through html beginForm but the method called is always [httpPost] index instead of the method specified in the post (Search).
What could I be doing wrong?
Here's my form:
#using (Html.BeginForm("Search", "MyController", FormMethod.Post))
{
<p>
Postal Code: #Html.TextBoxFor(m => m.PostalCode) <br />
City: #Html.TextBoxFor(m => m.PostalCodeCity ) <br />
Address: #Html.TextBoxFor(m => m.Address) <br />
<input type="submit" value="submit" />
</p>
}
My model:
public class MyModel
{
public string PostalCode { get; set; }
public string PostalCodeCity { get; set; }
public string Address { get; set; }
}
My Routes:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Ignore("{resource}.axd/{*pathInfo}");
//Routing for ASP.NET MVC Controllers
routes.MapRoute(
name: "ControllersRoute",
url: "mvc/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional });
//Routing for Web Api Controller
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
My controller methods
public class MyController : Controller
{
/// <summary>
/// Gets or sets the message.
/// </summary>
[Category("String Properties")]
public string Message { get; set; }
/// <summary>
/// This is the default Action.
/// </summary>
public ActionResult Index()
{
MyModel model = new MyModel();
return View("Default", model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
//Refresh model attending session variables
return View("Default", model);
}
[HttpPost]
public ActionResult Search(MyModel model)
{
//model work
return View("Default", model);
}
}
UPDATE
#markpsmith recommended me to check the form action and it was wrong.
it was action="order-calendar" than I Change it to action="order-calendar/search" and the action Search was called.
Is this a Route Problem?

I see you have tagged Sitefinity, If so you should be try:
#using Telerik.Sitefinity.UI.MVC;
#using Telerik.Sitefinity.Frontend.Mvc.Helpers
#using(Html.BeginFormSitefinity()){}

The BeginForm helper use the routing engine to reach the "search" action of your controller. That helper use a method named GetVirtualPath() in the RouteTable class (something like RouteTable.Route.GetVirtualPath()).
If you are using the same page for the post action you can simply use the
#using (Html.BeginForm())
without any param. Can you reach the "search" action using an URL compatible to your routing settings?

Related

Contact us form action not found

Not sure why this isn't working, but I suspect it's something to do with routing... (Using MVC5)
When clicking on the submit button I get the following message:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /contact
Using a model as follows:
public class EmailMessageModel
{
/// <summary>Gets or sets from name.</summary>
/// <value>From name.</value>
[Required, Display(Name = "Name")]
public string FromName { get; set; }
}
The view is then as follows:
#model EmailMessageModel
#using (Html.BeginForm("index", "contact", FormMethod.Post, new { enctype = "multipart/form-data", #class = "contact-form" }))
{
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.FromName, new { #class = "control-label" })
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
<input type="submit" value="Send Message" id="btnSubmitQuery" />
}
Controller is as follows:
(the breakpoint on the HttpPost Index action is never hit, any ideas why?)
namespace ExternalSite.Controllers
{
using ExternalSite.Models;
using System.Net.Mail;
using System.Web.Mvc;
[RoutePrefix("contact")]
public class ContactController : Controller
{
[HttpGet]
[Route]
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailMessageModel model)
{
// !!!!!!!!!!BREAKPOINT HERE IS NEVER BEING HIT!!!!!!!!!!!
if (ModelState.IsValid)
{
}
return View(model);
}
}
The solution was to add the blank route attribute [Route] to the HttpPost Index method, i.e.
[HttpPost]
[Route]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailMessageModel model)
{
// !!!!!!!!!!BREAKPOINT HERE IS NEVER BEING HIT!!!!!!!!!!!
if (ModelState.IsValid)
{
}
return View(model);
}

BeginForm Always calling Index when submitting

I'm using MVC BeginForm to submit form data to my ActionMethod in Controller. The problem is that when every I click on submit button it keeps calling Index method instead of Actual method defined in BeginForm.
Here is my View
#model HRMS.DBModel.department
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("save", "Department", FormMethod.Post))
{
#Html.TextAreaFor(model => model.Name, new { #class = "form-control" })
<input type="submit" value="submit" />
}
and here is the Department Controller
public class DepartmentController : Controller
{
// GET: Department
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult save()
{
return View();
}
}
and RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Location", action = "Index", id = UrlParameter.Optional }
);
}
I searched on google even found solutions but still my problem is still there.
Any help will be appreciated.
Thanks
Issue Resolved there was a form tag inside my Master page due to which it was calling Index Method, I removed that form tag and now its working fine

Inserting a User through ActionController using Entity Framework

I am trying to add a new User in my database, but every time I press submit i get this error
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. "
This is my controller:
public class CreateController : Controller
{
// GET: Create
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(User user)
{
using (var db = new UserEntities())
{
User newUser = new User();
newUser.Name = user.Name;
db.Users.Add(newUser);
db.SaveChanges();
return View();
}
}
}
This is my view:
#model FormulörModul.Models.User
<title>Create</title>
#using (Html.BeginForm("Create", "CreateController", FormMethod.Post))
{
<label>Namn</label>
#Html.TextBoxFor(m=>m.Name)
#Html.ValidationMessageFor(m => m.Name)
<input id="Submit1" type="submit" value="submit" />
}
I think the error is in the call to Html.BeginForm. By convention in MVC, when you name a controller you just name the string before "Controller". I.e. replace this
#using (Html.BeginForm("Create", "CreateController", FormMethod.Post))
with this
#using (Html.BeginForm("Create", "Create", FormMethod.Post))
BTW, "Create" is a really bad name for a controller. I would name it "User".

BeginForm in ChildAction uses wrong id

There is something simple I don't understand with ChildActions.
I've created a simple View for a model, that loads a child action with a form.
The child action has another model than its parent, with a different id property.
Html.HiddenFor(m => m.Id) still outputs the parents id, although #Model.id outputs the correct value!
Can't I reliably use the Helper methods in ChildActions, or is this a known bug?
HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Models.HomeModel { id = 1, message = "bugmodel" };
return View(model);
}
[HttpGet]
[ChildActionOnly]
public ActionResult Child(int id)
{
var model = new Models.HomeChildModel { id = 100, parentId = id, childMessage = "My Child message" };
return PartialView(model);
}
[HttpPost]
[ActionName("Child")]
[ValidateAntiForgeryToken()]
public ActionResult ChildPost(Models.HomeChildModel model)
{
return RedirectToAction("Index");
}
}
Models
public class HomeModel
{
public int id { get; set; }
public string message { get; set; }
}
public class HomeChildModel
{
public int id { get; set; }
public int parentId { get; set; }
public string childMessage { get; set; }
}
Home view
#model ChildActionBug.Models.HomeModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DisplayFor(m=>m.id)
#Html.DisplayFor(m=>m.message)
#Html.Action("Child", new { id = Model.id })
**Child view**
#model ChildActionBug.Models.HomeChildModel
<h3>Child here</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m=>m.id)
#Html.HiddenFor(m=>m.parentId)
#Html.EditorFor(m=>m.childMessage)
<div>Child Model ID: #Model.id</div>
<button type="submit">Save</button>
}
Based on the answer given in the SO question I posted in the comment, you're better off explicitly creating the hidden fields
ASP.Net MVC Html.HiddenFor with wrong value
That's normal and it is how HTML helpers work. They first use the
value of the POST request and after that the value in the model. This
means that even if you modify the value of the model in your
controller action if there is the same variable in the POST request
your modification will be ignored and the POSTed value will be used.
So instead, hand craft the hidden fields:
<input type="hidden" name="Id" value="#Model.Id" />
<input type="hidden" name="ParentId" value="#Model.ParentId" />
<input type="hidden" name="ChildMessage" value="#Model.ChildMessage" />

How do I get a strongly typed DropDownList to bind to a control Action

I've just started a new MVC project and I'm having trouble getting the post result from a form.
This is my Model Class :
public class User
{
public int id { get; set; }
public string name { get; set; }
}
public class TestModel
{
public List<User> users { get; set; }
public User user { get; set; }
public SelectList listSelection { get; set; }
public TestModel()
{
users = new List<User>()
{
new User() {id = 0, name = "Steven"},
new User() {id = 1, name = "Ian"},
new User() {id = 2, name = "Rich"}
};
listSelection = new SelectList(users, "name", "name");
}
}
This is my view class
#model MvcTestApplicaiton.Models.TestModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.user, #Model.listSelection)
<p>
<input type="submit" value="Submit" />
</p>
}
#if (#Model.user != null)
{
<p>#Model.user.name</p>
}
And this is my controller :
public class TestModelController : Controller
{
public TestModel model;
//
// GET: /TestModel/
public ActionResult Index()
{
if(model ==null)
model = new TestModel();
return View(model);
}
[HttpPost]
public ActionResult Test(TestModel test)
{
model.user = test.user;
return RedirectToAction("index", "TestModel");
}
}
The drop down list appears just fine but I can't see to get the ActionResult Test function to run. I thought it would just bind itself with reflection but whatever is wrong, I can't see it.
You have two main errors in your code.
As Brett said you're posting to the Index method, but you don't have Index method that supports POST verb. The easiest way to fix is to change Html.BeginForm() with Html.BeginForm("Test", "TestModel")
You're using Html.DropDownListFor in a wrong way. You could pass only a value types there, because don't forget that the View will generate an HTML page. So instead of User in your Model you should have an UserID and in your View you should have #Html.DropDownListFor(x => x.UserID, #Model.listSelection). And finally in your Action you should query your data source to get the details for the user with this ID.
Hope this helps.
Looks like you're posting back to index. Either use a GET Test() action method, or specify the ACTION parameter in BeginForm().
For example,
#using (Html.BeginForm("Test", "TestModel"))
{
#Html.DropDownListFor(x => x.user, #Model.listSelection)
<p>
<input type="submit" value="Submit" />
</p>
}
Or use a view named Test (rename index.cshtml to test.cshtml):
public ActionResult Test()
{
if(model ==null)
model = new TestModel();
return View(model);
}

Resources