mvc4 receive form in a controller - c#

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.

Related

C# MVC form does not send data back to controller

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.

Calling C# function By action [duplicate]

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!

Why this Action Method is not receiving any value from the form?

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");
}

.Net Core RC2 MVC parameter is null in controller

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();
}

POST data to controller with ASP.NET MVC

I am using ASP.NET MVC with C# and pure bootstrap. One of my views contains a label, text input box, and a submit button:
#{
ViewBag.Title = "BinSearch";
Layout = "~/Views/Shared/_LayoutSearch.cshtml";
}
<h2>BinConfig Search</h2>
#using (Html.BeginForm("FiEdit", "EditConfigController"))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
When I click the "submit" button, I would like to transfer the data to a controller, EditConfigController to this method:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey().Key = key);
}
Which then is supposed to create a new view where I can edit data based off the key provided. This is the FiEdit view:
#model BinFiClient.Models.IssuerKey
#{
ViewBag.Title = "FiEdit";
Layout = "~/Views/Shared/_LayoutEdit.cshtml";
}
<h2>FiEdit</h2>
However, when I click the "submit" button, I receive a 404 error, and the URL path looks like this:
http://localhost:58725/EditConfigController/FiEdit
Which is actually the path to the method in the controller that I posted above.
What I need is basically a way to POST data to another controller. How can I accomplish this?
Edit:
Now I am receiving the error:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'BinFiClient.Models.IssuerKey'.
Try replacing your code with the following:
#using (Html.BeginForm("FiEdit", "EditConfig", FormMethod.Post))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
This will POST the parameter key to the EditConfig controller.
If you'd like to post to the action TestEdit in another controller, say the TestController, your code should be changed to the following:
#using (Html.BeginForm("TestEdit", "Test", FormMethod.Post))
...
To resolve the "model item passed into the dictionary" error, change your POST to be this:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey() { Key = key });
}
ou can try with:
#using (Html.BeginForm(("FiEdit", "EditConfigController", FormMethod.Post,
new { enctype = "multipart/form-data" })))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}

Categories

Resources