Using .NET Core RC2 in VS Code I have the following HTML
<form asp-controller="Home" asp-action="Connexion" method="post">
<div class="col-md-4 input-group">
<input type="text" id="password" class="form-control" placeholder="Mot de passe">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Envoyer</button>
</span>
</div>
</form>
And a controller
[HttpPost("/Connexion")]
public IActionResult Connexion([FromBody] string password)
{
return View();
}
When submitting the form, it hits my breakpoint in the method but the password parameter is null. What do I do wrong?
The form field name should match with the parameter name. So add a name attribute.
<input type="text" name="password" class="form-control" placeholder="Mot de passe">
You may also remove the [FromBody] decoration.
[HttpPost("/Connexion")]
public IActionResult Connexion(string password)
{
return View();
}
Related
I know it must be something stupid, but I cant seem to figure this out. I have the following in a view:
#using (#Html.BeginForm("ReceiveForm1", "Home", FormMethod.Post))
{
<div class="form-group">
<label for="organizationID">Organization ID</label>
<input type="number" class="form-control" asp-for="organizationID" aria-describedby="emailHelp" placeholder="Enter Organization ID">
</div>
<div class="form-group">
<label for="externalPersonalID">External Personal ID</label>
<input type="number" class="form-control" asp-for="externalPersonalID" placeholder="Enter External Personal ID">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="number" class="form-control" id="phoneNumber" asp-for="phoneNumber" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
}
And I have the following code in my controller:
[HttpPost]
public ActionResult ReceiveForm1(FormCollection collection)
{
IEnumerable<Form1Return> personData = GetPersonInformation(collection);
return View(personData);
}
When I run the code, and enter data into the form, and click the submit button, I run to a breakpoint set on call to GetPersonInformation. When I do a watch on collection, there are no elements. So for some reason, the form data is not making it to the controller. Any idea why?
Thanks.
The 'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinder' cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'. Change the model type to 'Microsoft.AspNetCore.Http.IFormCollection' instead.
Please try this:
[HttpPost]
public ActionResult ReceiveForm1(IFormCollection collection)
{
IEnumerable<Form1Return> personData = GetPersonInformation(collection);
return View(personData);
}
I've seen this happen when input's don't have their name attribute set. The relevant section on W3Schools has this nugget which confirms this is likely the case.
Note: Only form elements with a name attribute will have their values passed when submitting a form.
I have a basic form for which I want to handle buttons inside the form by calling the ActionResult method in the View's associated Controller class. Here is the following HTML5 code for the form:
<h2>Welcome</h2>
<div>
<h3>Login</h3>
<form method="post" action= <!-- what goes here --> >
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
</form>
</div>
<!-- more code ... -->
The corresponding Controller code is the following:
[HttpPost]
public ActionResult MyAction(string input, FormCollection collection)
{
switch (input)
{
case "Login":
// do some stuff...
break;
case "Create Account"
// do some other stuff...
break;
}
return View();
}
you make the use of the HTML Helper and have
#using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="#Url.Action("MyAction", "MyController")" >
Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
#using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>#Model.Title</strong> will be deleted.</p>
#using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
#Url.ActionLink("go to list", "Index")
}
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/ActionMethod?userName=#Model.UserName">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
<form class="form-inline" asp-controller="Search" asp-action="Index">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-primary" type="submit">Search</button>
</form>
This moves us to the controller:
public IActionResult Index(string query)
{
//get data
return View(data);
}
But obviously query is always empty, because I'm not sending it as parameter. Question is how to do it? It's easy when you have some model in view, but I don't know how to bind these two without model.
Try it with adding a name attribute to the input and set its value to the parameter name:
<input name="query" class="form-control mr-sm-2" type="text" placeholder="Search">
How to pass some value from the form to the controller using the FormCollection method. But the controller return null.And the form is located inside a modal popup window..
View
<form action="/Home/AddToCart" method="post">
<input type="hidden" id="vid" name="vid" class="hiddenid" />
<div class="styled-input agile-styled-input-top">
<input type="text" placeholder="Name" name="name" id="name" required>
</div>
<div class="styled-input">
<input type="text" placeholder="Star Name" name="star" id="star" required>
</div>
<input type="submit" value="Add To Cart">
</form>
Controller
[HttpPost]
public ActionResult AddToCart(FormCollection data) {
var cart = new cart {
vid = Convert.ToInt32(data["vid"]),
name = data["name"],
star = data["star"]
};
userService.AddToCart(cart);
ViewBag.p = userService;
return RedirectToAction("Temple");
}
i have a form in html and i want to submit it to a controler
what i have tried
#using (Html.BeginForm("RegisterApartmentOwner", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<p>
<label>First Name</label>
<input type="text" placeholder="Enter your first Name" name="firstName" />
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" placeholder="Enter your last Name" />
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="text" placeholder="Enter your password" name="Password"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password Again</label>
<input type="text" placeholder="Enter your password again" name="Password2"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" placeholder="Enter your mobile number" />
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" value="Register" class="submit"/>
</p>
}
</div>
and in the controller i receive the submit in this function
public String RegisterTenant() {
return "done";
}
i can see the done message, however, i want to receive the values of the input that i used in the form, how please?
i just to know what to receive the form in the controller
You could accept the formcollection (as in: FormCollection collection) as a parameter in your post action, or, better yet, create a view model, send that to the view and post it to the controller. You'd have to set it as a parameter of your http post action course.
Example:
[HttpPost]
public String RegisterTenant(FormCollection collection) {
// give all your html elements you want to read values out of an Id, like 'Password'
var password = collection["Password"];
// do something with your data
return "done";
}
Or (better!):
View model:
public class HomeViewModel
{
[Required]
public string UserName {get;set;}
}
View (on top):
#model Namespace.HomeViewModel
View (in your form):
#Html.TextBoxFor(m => m.UserName)
Controller:
[HttpPost]
public String RegisterTenant(HomeViewModel model)
{
var userName = model.UserName;
// do something
}
But you should really do some investigation into MVC: Views, Models & Controllers and what they do. It is really better to create a typesafe view model and work with that.