BeginForm Always calling Index when submitting - asp.net-mvc

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

Related

HTTP POST fails when view has default name (route config)

The post of a view fails. It seems like the action name is missed.
If I change the POST action name in both controller and view to another arbitrary name, it works.
Controller
public class AuthenticationController : Controller
{
// GET: Authentication
[HttpGet]
public ActionResult Index()
{
var model = new IndexViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
if (ModelState.IsValid)
{
if(Membership.ValidateUser(model.Username, model.Password))
{
return RedirectToAction("Index", "Default");
}
else
{
model.ErrorMessage = "Failed to login. Please try again!";
}
}
return View(model);
}
}
View
#model Test.Web.Models.Authentication.IndexViewModel
#{
ViewBag.Title = "Log In";
}
<h2>Enter credentials to log on</h2>
#using (Html.BeginForm("Index", "Authentication"))
{
<p>
#Html.LabelFor(x => x.Username)<br />
#Html.TextBoxFor(x => x.Username)
</p>
<p>
#Html.LabelFor(x => x.Password)<br />
#Html.TextBoxFor(x => x.Password)
</p>
<input type="submit" value="Log In" />
}
I'm pretty sure the reason is the RouteConfig and the default action name.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
One solution is of course to rename both the GET and POST action, and not use Index, but is there a way of getting this to work as it is? Without any hack, that is.

MVC ActionLink 404 Error

Hi Guys' I am getting HTTP 404 in my MVC project and I am not sure where it is coming from.
On the _NavBar I have an ActionLink control that is calling to CreateSite
<li>
#Html.ActionLink("Create Location","CreateSite", "SiteRegistration", routeValues: null, htmlAttributes: new { id = "registerLink" })
</li>
I have an Controller name SiteRegistrationController
public class SiteRegistrationController : Controller
{
SiteInfoManager manager = new SiteInfoManager();
//
// GET: /SiteRegistration/
public ActionResult UserSiteResult()
{
return View();
}
}
The views I have are Folder SiteRegistration and CreateSite.cshtml.
The Error is coming from the SiteInfoManager line in the Controller.
Any help would be great.
You need to update your #Html.ActionLink to:
#Html.ActionLink("Create Location","UserSiteResult", "SiteRegistration", new { id = "registerLink" }, null)
And update your Controller:
public ActionResult UserSiteResult(string id)
{
// you can use id now, as it will be regirsterLink
return View();
}

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".

HTML.BeginForm sends Post always to index action

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?

ASP.NET MVC Search Results Page MapRoute Doesn't Work

How can i set mapRoute for search results page? My code doesn't work.
Global.asax.cs
routes.MapRoute(
name: "SearchResults",
url: "{action}/{Keyword}",
defaults: new { controller = "Home", action = "Search" }
);
Search Form
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#Html.TextBox("Keyword",null , new { #class = "SearchBox" })
<input type="submit" value="Search" />
}
HomeController.cs
public ActionResult Search(string Keyword)
{
GamesContext db = new GamesContext();
var SearchResults= (from i in db.Games where i.GameName.Contains(Keyword) || i.GameDesc.Contains(Keyword) select i).Take(20).ToList();
return View(SearchResults.AsEnumerable());
}
This one works for me (should be before default route):
routes.MapRoute(
"SearchResults",
"Search/{Keyword}",
new { controller = "Search", action = "SearchAction" }
);
Creating an ActionLink and MapRoute that there is a constant name in it
And there's a point to use new controller for search instead of home with this route.

Resources