Reputation: 63
I'm starting with ASP.net MVC, and I have two views. The first one is ViewPost, with a form, which I want that when pressed the input button, will send the info from the form to another view. My code is like this:
<h2>ViewPost</h2>
<form method="POST" action="~/Home/NewView">
Number<input id="id_number"type="text" name="name_number" />
Text<input id="id_text" type="text" name="name_text" />
<input type="submit"/>
</form>
In the controller I have this code:
[HttpPost]
public ActionResult ViewPost(int? name_number, string name_text)
{
return View();
}
Also in the controller I have a GET method for the NewView, which will check the values and concat them, and show the resultant String in a ViewBag.Message:
public ActionResult NewView(int? number, String name)
{
String urlParam = "";
if (number.HasValue)
{
urlParam += " Value number=" + number;
}
if (name != null)
{
urlParam += " Value name=" + name;
}
if (urlParam == "")
{
urlParam = "No values";
}
ViewBag.Message = urlParam;
return View();
}
when I press the submit button, I get
Resource not found. Requested URL: /Home/NewView
but when going by writing the URL I can go with no problems
Upvotes: 0
Views: 1762
Reputation: 218887
Your form is sending a POST
request:
method="POST"
But you claim to be expecting a GET
request:
in the controller I have a GET method for the NewView
Either change the form to a GET
request:
method="GET"
or change the controller action to accept a POST
:
[HttpPost]
public ActionResult NewView(int? number, String name)
{
//...
}
Additionally, the form element names must be the same as the variables you want them to populate. So either change them in the form:
name="number"
...
name="name"
or change them in the action method:
public ActionResult NewView(int? name_number, String name_text)
A note on terminology which may clear some of this up for you...
which I want that when pressed the input button, will send the info from the form to another view
This is incorrect. You don't send values to a view, you send them to a controller action. Anything that goes to the server is generally going to a controller action. That action method can do whatever it needs to do with those values, including returning a view.
But the overall interaction is that the in-browser code (a link, a form, JavaScript and AJAX, etc.) makes requests to server-side actions and those actions return a variety of responses.
Upvotes: 1