ASP.NET MVC 3 - two forms, two ActionResult but one Controller? - asp.net-mvc

I have a new asp.net mvc 3 project with following structure:
Views:
/Home/Index.cshtml
#{
Html.BeginForm("Index", "Home", "POST");
}
<input id="name" type="text" />
<input id="submit_1" type="submit" value="submit" />
#{
Html.EndForm();
}
#{
Html.BeginForm("FindTeacher", "Home", "POST");
}
<input id="name" type="text" />
<input id="submit_2" type="submit" value="submit" />
#{
Html.EndForm();
}
Controller:
/Controllers/HomeController.cs
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index(string name)
{
//call the model FindStudent() and set the ViewData
return View();
}
[HttpPost]
public ActionResult FindTeacher(string name)
{
//Call the FindTeacher () and set the ViewData
return View();
}
}
The submit_1 is works, because it found the ActionResult of Index, however, when i click submit_2, it say cannot find FindTeacher Controller.
So how can i do?

Try this
[HttpPost]
public ActionResult FindTeacher(string name)
{
// do updates
return RedirectToAction("Index"); or
return Index();
}

"POST" is wrong; it should be FormMethods.Post.
Because of that, your forms are actually submitting GET requests.
Index works because you have a different action that responds to GET requests to /Index.
FindTeacher fails because there is no GET for that action.

Related

httpPost return Page not found HTTP ERROR 405 ASP.NET CORE MVC IIS Express

i have problem with form when i put in my Controller httpPost the Error http 405 it showing to me
every step i made its correct
my code
#model security.Models.ContactUs
<div class="contact_box">
<form id="Contact" asp-controller="Home" asp-action="Contact" method="POST">
<input type="text" asp-for="Name" placeholder="Your Name">
<input type="email" asp-for="Email" placeholder="Email">
<input type="text" asp-for="PhoneNumber" placeholder="Phone Number">
<input type="text" asp-for="Text" placeholder="Message">
<button type="submit">Contact Us</button>
</form>
</div>
and my Controller
namespace security.Controllers
{
public class HomeController : Controller
{
DBContext db;
public HomeController(DBContext context)
{
db = context;
}
//private readonly ILogger<HomeController> _logger;
//public HomeController(ILogger<HomeController> logger)
//{
// _logger = logger;
//}
[HttpGet]
public IActionResult Index()
{
CollectionsData model = new CollectionsData();
model.Offers = GetOffers();
model.Services = GetServices();
model.News = GetNews();
model.Team = GetSecurityTeam();
return View(model);
}
[HttpPost]
public IActionResult Contact(ContactUs model)
{
db.Contactus.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult Services( Sevices model)
{
var ModelServices = db.Sevices.ToList();
return View(ModelServices);
}
//[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
//public IActionResult Error()
//{
// return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
//}
public IEnumerable<Offers> GetOffers()
{
return db.Offers.ToList();
}
public IEnumerable<Sevices> GetServices()
{
return db.Sevices.ToList();
}
public IEnumerable<ourNews> GetNews()
{
return db.News.ToList();
}
public IEnumerable<SecurityTeam> GetSecurityTeam()
{
return db.Team.ToList();
}
}
}
But when I delete httppost everything works fine except sending the form to the database
i don't why the page its not load its give HTTP ERROR 405
thanks
you have to place a submit button inside of the form
<form asp-controller="Home" asp-action="Contact" method="POST">
....your code
<button type="submit">Contact Us</button>
</form>
or for some reason sometimes this works better
#using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
....your code
<button type="submit">Contact Us</button>
}
and you need Contact get action to create a contact view
[HttpGet]
public IActionResult Contact()
{
var model= new ContactUs();
return View(model)
}
try this
<form id="contact" method="POST" asp-action="Contact">
...
</form>
return View() doesn’t make any sense from an HTTP Verb perspective. Your form is POSTing correctly, but when you’re returning the view you need to change it to redirect to your GET action. I don’t know know what your entire controller looks like but I suspect this is the issue with naming.
Try
return RedirectToAction(“VIEWNAME”)

How to check each form controller's type posted to action method?

View:
#using (Html.BeginForm())
{
#Html.Label("WebLinkLabel")
#Html.Editor("WebLinkTextbox")
#Html.Label("WebEnabledLabel")
#Html.CheckBox("WebEnabledCheckbox")
<input name="Save" type="submit" value="Save" />
}
Action Method:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
foreach (var key in collection.AllKeys)
{
var typee = collection.GetType();
}
return View();
}
GetType() gives me that:
collection.AllKeys.GetType()
{Name = "String[]" FullName = "System.String[]"} System.Type {System.RuntimeType}
I would like to know like the first controller is of type Textbox, another one is Checkbox etc..

how to pass data from view to controller

I am new to asp.net MVC5 and i am trying to pass data from view to controller as a string.
Here is controller class:
namespace Movies.Controllers
{
public class HelloWorldController : Controller
{
// GET: HelloWorld
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult welcome(FormCollection fc, string reportName)
{
ViewBag.Message = reportName;
return View();
}
}
}
Here is Index View:
#{
ViewBag.Title = "MVC Movies";
}
<h2>My Movies List</h2>
<p>Hellow from our view template</p>
#using (Html.BeginForm("Welcome", "HelloWorld", FormMethod.Get))
{
<p>
<input type="text" name="reportName" />
<input type="submit" />
</p>
}
Here is welcome view:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>welcome</h2>
#{
ViewBag.Title = "Welcome";
}
<ul>
#for (int i = 0; i < 2; i++)
{
<li>#ViewBag.Message</li>
}
</ul>
Actually my Index method is passing a view that will have a textbox for string in it in a form and then on clicking submit button application should pass that string in the Welcome method in the same controller. On clicking submit button browser is showing a windows that resources con't be found.
Whats the problem..? thank you for your time..:)
1) The action name is case sensitive, you are using "Welcome" in the form definition , but the action must has the name "welcome" with w lower case.
2) Your form is doing a GET but you are specting a POST in the action
[HttpGet]
public ActionResult welcome(FormCollection fc, string reportName)
{
ViewBag.Message = reportName;
return View();
}
Replace FormMethod.Get with FormMethod.Post in your beginform.
Modify FormMethod.Get to FormMethod.Post:
#using (Html.BeginForm("Welcome", "HelloWorld", FormMethod.Post))
{
<p>
<input type="text" name="reportName" />
<input type="submit" />
</p>
}
Change your action implementation to this:
[HttpPost]
public ActionResult welcome(FormCollection fc)
{
ViewBag.Message = fc["reportName"];
return View();
}
However, I'd strongly suggest that you create a view model for your form and use it instead of FormCollection.

ASP.NET MVC Html.BeginForm decodes URL

I'm requesting ASP.NET MVC the controller using the URL like this:
http://mysite.com/controller/myaction/Invalid%23name%25x
where Invalid%23name%25x is a parameter to
public ActionResult MyAction(string id) {
return View();
}
The GET request works fine.
MyAction view looks like this:
#using (Html.BeginForm()) {
...
<input name="Save" type="submit" value="Save" />
}
The generated HTML is:
<form action="/Controller/MyAction/Invalid#name%x" method="post">
...
<input name="Save" type="submit" value="Save" />
</form>
When I click on "Save", the form gets posted and the POST request goes to
http://mysite.com/controller/myaction/Invalid#name%x
i.e. the initial URL is decoded. This means the the POST action receives only the first part of the parameter - "Invalid"
[HttpPost]
public ActionResult MyAction(string id, ...) {
return View();
}
How can I prevent Html.BeginForm from decoding the initial URLs in order to preserve the initial state?
Pass ActionName and Controller in your form
#using (Html.BeginForm("ActionName", "Controller")) {
I would personally recommend you not to use id as string because as you have seen string can have many words in it.. let it mean what usually it does(numeric value).
use something like http://mysite.com/controller/myaction?Name=Invalid%23name%25x
public ActionResult MyAction(string Name) {
return View();
}
I suppose this would work for you..

how to get the parameters of a request from a view in controller

I am new to mvc and I want to know how to get the parameters of a request from a view.
This is my code for view:
#using (Ajax.BeginForm("LoadPartialView", new AjaxOptions())) {
<input type="submit" value="Submit" id="submit1"/> }
I want to get the value Submit or id submit1 in action method LoadPartialView of the controller. How can I achieve this?
Without knowing anything about your view model or controller methods, you can get the value by doing the following:
View:
#using (Ajax.BeginForm("MyAction", new AjaxOptions())) {
<input type="submit" name="submit" value="Submit" id="submit1"/>
}
Controller:
[HttpPost]
public ActionResult MyAction(FormCollection f)
{
var submitValue = f["submit"];
}
Alternatively, type your view to a model with a submit property and pass this to your controller method, doing something like the following:
Model:
public class MyModel
{
public String Submit { get; set; }
}
View:
#model MyModel
#using (Ajax.BeginForm("MyAction", new AjaxOptions())) {
<input type="submit" name="Submit" value="Submit" id="submit1"/>
}
Controller:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
var submitValue = model.Submit;
}
The latter model is obviously more extensible as you can then group this value with other form values.
You need name attribute for any input field to be serialized by default to the FormcCollection, for example:
<input type="text" value="yourvalue" name="yourname" id="yourid"/>
Then you can retrieve such value in following way:
public ActionResult YourAction(FormCollection formCollection)
{
var val = formsCollection["yourname"];
//...
}

Resources