How to retrieve form values from HTTPPOST, dictionary or? - asp.net

I have an MVC controller that has this Action Method:
[HttpPost]
public ActionResult SubmitAction()
{
// Get Post Params Here
... return something ...
}
The form is a non-trivial form with a simple textbox.
Question
How I access the parameter values?
I am not posting from a View, the post is coming externally. I'm assuming there is a collection of key/value pairs I have access to.
I tried Request.Params.Get("simpleTextBox"); but it returns error "Sorry, an error occurred while processing your request.".

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}

Simply, you can use FormCollection like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.
Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.
<input type="hidden" name="TrackingID"
<input type="text" name="FirstName" id="firstnametext" />
<input type="checkbox" name="IsLegal" value="Do you accept terms and conditions?" />
Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.
[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}
You can also post back a model without using any razor helpers. I have come across that this is needed some times.
public Class HomeModel
{
public int HouseNumber { get; set; }
public string StreetAddress { get; set; }
}
The HTML markup will simply be ...
<input type="text" name="variableName.HouseNumber" id="whateverid" >
and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.
[HttpPost]
public ActionResult PostBack(HomeModel variableName){
postBack.HouseNumber; //The value user entered
postBack.StreetAddress; //the default value of NULL.
}
When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.
TIP: The name of the parameter in the controller is the name defined
in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !
Using List<> is bit more complex in its mark-up.
<input type="text" name="variableNameHere[0].HouseNumber" id="id" value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber" value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">
Index on List<> MUST always be zero based and sequential. 0,1,2,3.
[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
int counter = MyHomes.Count()
foreach(var home in MyHomes)
{ ... }
}
Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.
<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id" value="3">
<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3" value="4">
<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23" value="5">
And the code just needs to use IEnumerable and call ToList()
[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
int counter = variableNameHere.ToList().Count()
foreach(var home in variableNameHere)
{ ... }
}
It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.
So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:
[HttpPost]
public ActionResult SubmitAction() {
// This will return an string array of all keys in the form.
// NOTE: you specify the keys in form by the name attributes e.g:
// <input name="this is the key" value="some value" type="test" />
var keys = Request.Form.AllKeys;
// This will return the value for the keys.
var value1 = Request.Form.Get(keys[0]);
var value2 = Request.Form.Get(keys[1]);
}

Related

Is using Viewbag for remembering past form inputs a bad idea?

I have a small asp.net core mvc application that basically consists of a form that a user can input some constraints into, and then get a filtered list of data depending on those constraints.
The controller action for filtering data basically looks like this:
[HttpPost]
public async Task<IActionResult> Query(QueryModel query)
{
var customers = await _context.Customers.AsQueryable().FilterCustomerList(query);
return View("Index", customers);
}
Now, my issue is that I would like the inputs in the fields to persist after entering them and being redirected to the view again. Right now they are currently just reset.
One way of doing this that I found was using viewBag. An example for a single query attribute is this:
public async Task<IActionResult> Query(QueryModel query)
{
var customers = await _context.Customers.AsQueryable().FilterCustomerList(query);
ViewBag.Name = query.Name;
return View("Index", customers);
}
and then the inpuit html elelment would look like:
<div class="col-md-4">
<input name="Name" type="text" placeholder="First name" value="#ViewBag.Name"class="form-control">
</div>
And this makes sure that if something has been entered into a field, it will now be entered into the field when after the query has been submitted.
But when I read up on ViewBag, I understand that a lot of .net developers have an aversion to it. It's not safe, the compiler can't catch errors in it easily etc.
Also, If I were to add all the input fields in my form to the viewbag, I would need a lot of lines of ViewBag.Attribute = query.SomeAttribute (20-30). Which seems like a code-smell too.
Is there any nicer way to do what I am trying to here?
You haven't included your QueryModel class and that class could be a key point to a cleaner approach.
You see, usually the user data, POSTed to your action is bound to the model, from there it's rendered on the form and is POSTed again. The model binding is where an input of a specific name is bound to a model member of the same name.
Thus, there's no need for viewbags.
More formally:
The Model
public class QueryModel
{
[your-validators-in-attributes, e.g. Required or MaxLength
there can be multiple validators]
public string Name { get; set; }
}
The controller:
[HttpPost]
async Task<IActionResult> Query(QueryModel query)
{
// query.Name is there, bound from the view
}
The View:
#model .....QueryModel
<div>
#Html.TextBoxFor( m => m.Name, new { placeholder = "a placeholder" } )
</div>
The html helper does two things
renders an input of the given name (Name in this case)
sets its value depending on the actual value from the model
In newer ASP.NETs you can achieve similar result by using tag helpers, where instead of Html.TextBoxFor(...) you write
<input asp-for="Name" />
These two approaches, using html helpers or using tag helpers are equivalent. In both cases there's no need for view bags.

Set and Get the default value of checkbox in ASP.NET mvc

I am using Checkbox in my ASP.Net MVC project,
I can set check box by default as unchecked.
Age:
<input class="associationCheckbox" type="checkbox" name="age" />
When I post the form (For has only checkbox), the checkbox is not showing in formCollection (Here expected name and value are age, ‘false’).
Using below code,I was reading the velues.
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
foreach (var key in formCollection.Keys)
{
var value = formCollection[key.ToString()];
}
return RedirectToAction("CorticonIndex", "Test");
}
If I check the check box at run time, then submit the form.
I can get the name and value.
How to get the default values(false)If I don’t check checkbox?
I tried setting value property using model property but same issue is coming.
Model Class:
public bool CheckBoxvalue { get; set; }
this.CheckBoxvalue=false
Age: <input class="associationCheckbox" type="checkbox" name="age" value=#Model.CheckBoxvalue />
Can someone suggest me how to set and get default value.
I had look at below post from stack overflow but didn't info for my requirement.
How to set a CheckBox by default Checked in ASp.Net MVC
http://www.tutorialsteacher.com/mvc/htmlhelper-checkbox-checkboxfor
Thanks,
Balu
You can do something like this:
Age: <input class="associationCheckbox" type="checkbox" name="age" #(Model.CheckBoxvalue ? "checked" : "") value=#Model.CheckBoxvalue />
But it is always good to use HTMLHelper methods if you are using razor

Passing data from View to Controller in ASP.NET MVC

I have a model class Person
public class Person
{
public string name { get; set; }
public string area { get; set; }
}
Now, in my Index view, I want to pass values from view to controller by taking value name property from user and area ="foo".I know how I can take values from user by like below
#using (Html.BeginForm())
{
#Html.Label("Name")
#Html.TextBoxFor(m=>m.name)
<input type="submit" value="Name" />
}
Now, I want area ="foo" in views.I tried to google the problem,I did not find the solution.
This is general problem.Do not answer like ,set value area="foo" in controller.
Please help me and don't downvote without commenting so that I can improve my question in future.
Thanks
Add a hidden field to your form with name "area" and set the value as whatever you want. When your form is posted, the hidden field value will be also posted to your action method.
#using (Html.BeginForm())
{
#Html.Label("Name")
#Html.TextBoxFor(m=>m.name)
<input type="hidden" name="area" value="foo" />
<input type="submit" value="Name" />
}
Now you can get this in your HttpPost action method
[HttpPost]
public ActionResult Create(Person model)
{
// check for model.name and model.area.
// TO DO : Save and redirect
}
You should remember that, people can always update the hidden field value in the browser using some tools like firebug or so. If it is a sensitive information (Price of an item in a shopping portal) , don't read like this from client. Read it from server.

How to pass a list of object from view to controller in mvc3?

public class EmployeeViewModel
{
public Employee Employee { get; set; }
public IList<Address> Addresses { get; set; }
}
Controller :-
[HttpPost]
public ActionResult InsertAddress(EmployeeViewModel model)
{
//code for insert data into db
}
View :-
Here i want to call InsertAddress action by passing multiple address objects along with single employee object from view to controller .
Is it possible ?
You just need to use the correct naming conventions for the model binder to understand.
Property.Property
Or
Property[index].Property for Collections
If index isn't sequential 0 based you need to add a hidden field, Property.Index with the value of the index
Example:
<input name="Employee.Name" value="1234 5678"/>
<input name="Employee.Phone value="1234 5678"/>
<input name="Employee.Email" value="me#example.com"/>
<input name="Addresses.Index" value="0" type="hidden"/>
<input name="Addresses[0].Suburb" value="Melbourne"/>
<input name="Addresses[0].Postcode" value="3000"/>
<input name="Addresses.Index" value="1" type="hidden"/>
<input name="Addresses[1].Suburb" value="Sydney"/>
<input name="Addresses[1].Postcode" value="2000"/>
When your inserting a row, just use the naming convention, and don't forget to add the .Index field.
Most the default EditorFor will handle all of this for you transparently if you create a custom EditorTemplate for your Address class.
Yes it possible, but requires a little work on your part.
Rather than having a single view for the model (with some sort of loop for the addresses), you need to create an EditorTemplate for your Address class, and then in the main view use #Html.EditorFor(m => m.Addresses)
This setup will cause your EmployeeViewModel instance to be returned to your action containing the full list of Addresses (rather than it being empty).
I have mentioned some common issues while binding complex models, have a look here
http://jayakarant.blogspot.de/2014/05/handling-complex-view-models-in-razor.html

Asp.net mvc3 razor with multiple submit buttons

I'm using MVC3 Razor. I have 2 submit buttons setup on my view but the problem I'm having is that both submit buttons cause the validation of the model. I want to hook up individual submit buttons with specific input controls for validation.
I know this is a few months old but the solutions here seemed needlessly complex and there's no accepted answer yet. If you name your inputs the same but give them different values, you can get that value in your controller just by including a string with the name of the input as a variable. This is how I solved this problem:
View:
<input type="submit" id="EnterprisePush" name="btnSubmit" value="Push" />
<input type="submit" id="EnterprisePull" name="btnSubmit" value="Pull" />
Controller:
[HttpPost]
public ActionResult EnterpriseAdmin(int id, string btnSubmit, FormCollection collection)
{
switch (btnSubmit) {
case "Push":
/* Do Something here */
break;
case "Pull":
/* Do Something else here */
break;
}
The browser is always going to submit the entire form regardless of which submit button you press.
The best solution would be to have two submit buttons with the same value for the name attribute and different values for the value attributes.
When you submit the form, the value of the button will be submitted as well. In your action which handles that form submission, you check to see the value of the button and perform the correct validation based on that.
In your form you would have something like this:
<button type="submit" name="Command" value="command1">Do Command #1</button>
<button type="submit" name="Command" value="command2">Do Command #2</button>
Your Form Model would look like this:
public class MyFormModel() {
public string Command {get;set;}
public string SomeOtherVal {get;set;}
}
Your controller\action would look like this:
public ActionResult HandleFormSubmit(MyFormModel model) {
if (model.Command == "command1") {
// do something
} else if (model.Command == "command2") {
// do something else
}
}
Firstly, you can disable client validation on your cancel button simply by adding the CSS class 'cancel' to it. See: Disable client-side validation in MVC 3 "cancel" submit button
Secondly, as well testing the submit element's form name as described above, you can use a custom action selector. Here's mine, which I originally took from the blog post shown in the comment:
/// <summary>
/// Used to vary an action method based on which button in a form was pressed. This
/// is useful but is an anti-pattern because it couples the controller to names
/// used in the form elements.
/// </summary>
/// <remarks>
/// See the example at http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
/// </remarks>
public class AcceptButtonAttribute : ActionMethodSelectorAttribute
{
public string ButtonName { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var req = controllerContext.RequestContext.HttpContext.Request;
return !string.IsNullOrEmpty(req.Form[this.ButtonName]);
}
}
In your controller:
[HttpPost]
[ActionName("Edit")]
[AcceptButton(ButtonName = "Cancel")]
public ActionResult Edit_Cancel(MyModel model)
{
return RedirectToAction("Index");
}
[HttpPost]
[AcceptButton(ButtonName = "Save")]
public ActionResult Edit(MyModel model)
{
// do real work here
}
Note that you need the [ActionName("Edit")] attribute to tell MVC that although using a different method name, it is for the Edit action.
And in your View:
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Cancel" value="Cancel" class="cancel" />
My solution was to do two things. Say we have a Save button and another Add Something button. When user clicks on Save we want client validation and server validation to be performed. For later button we don't want any validation to take place.
Temporarily disable client validation for second button (on click):
<input type="submit" name="submit-button" value="Save" />
<input type="submit" name="submit-button" value="Add Something" onclick="document.forms[0].noValidate = true; document.forms[0].submit();" />
Good thing about it is when JavaScript is disabled the client validation would never have taken place anyway.
Take care of server side
Similar to what Bryan is saying when you click any submit button within a form, the entire form and the clicked submit button value is posted. You can differentiate which button was clicked by the name posted. In example above when user clicks on Save button and we read Request.Form["submit-button"] in controller post action we get "Save". If user clicked on Add Something we would get "Add Something". This is the way HTML is supposed to work.
Now to get around having magic strings all over the place I usually have a public static class within the controller, like so:
public class HomeController
{
public static class Buttons
{
public const string Save = "Save";
public const string AddSomething = "Add something";
}
// Action methods
}
So you can use these for rendering form:
<input type="submit" name="submit-button" value="#HomeController.Buttons.Save" />
And you can easily read the button clicked in controller:
[HttpPost]
public ActionResult Index(Model viewModel)
{
var buttonClicked = Request.Form["submit-button"];
switch (buttonClicked) {
case HomeController.Buttons.Save:
return Save(viewModel);
case HomeController.Buttons.AddSomething:
return AddSOmething(viewModel);
}
return View();
}
In Save method you first ask if ModelState.IsValid and return view model if not but in AddSomething method we will clear any errors:
public ActionResult AddSomething(Model viewModel)
{
ModelState.Clear();
// your code to add something to model
return View(viewModel);
}
This was you keep everything clean, tidy and testable. And you can introduce a constant for submit-button html name attribute. It might be possible to do all the constants with T4MVC too. A similar solution applies to when you need a "auto postback" combo box, except you need a hidden field that is set via onchange event of the select element.
Hope this helps.
Just use this code as a template:
#{
var nextButtonVal = "Next >>";
var backButtonVal = "<< Back";
if (IsPost) {
if(Request["navigate"].Equals(backButtonVal)){Response.Redirect("~/pageFoo");}
if(Request["navigate"].Equals(nextButtonVal)){Response.Redirect("~/pagebar");}
}
}
<input type="submit" value="#backButtonVal" title="Back" name="navigate"/>
<input type="submit" value="#nextButtonVal" title="Next" name="navigate"/>
One final thing I would do is instead of using intelligent strings, use an enum to determine the value for each input tag. Using razor syntax:
#Enum.GetName(typeof(YourEnumType), yourEnum.WhateverValue)
then in your controller:
public ActionResult DoSomethingBasedOnEnumValue(string enumValue)
{
YourEnumType localVar = (YourEnumType)Enum.Parse(typeof(YourEnumType), enumValue);
switch(localVar)
{
case YourEnumType.Action1:
//do something
break;
case YourEnumType.Action2:
//do something else
break;
}
return View();
}
If you want to have separate action for delete, try this.
add a delete action in the controller and mark it as HttpDelete,
[HttpDelete]
public ActionResult Edit(int id, string foo) {
...
}
And in the view,
button name should be X-HTTP-Method-Override and value should be DELETE
<button name="X-HTTP-Method-Override" value="DELETE" formnovalidate="formnovalidate" class="cancel">Delete</button>
note: all most all the browsers don't allow for other HTTP methods, like HEAD, PUT, or DELETE. but by add a header to the HTTP request, X-HTTP-Method-Override, that is supposed to be interpreted by the service and acted upon regardless of the actual HTTP method used. So above code will add a header to the request like X-HTTP-Method-Override: DELETE. and .net framework will do the rest of the things and direct you to delete action.
Submit button name don't come to server side if in all from this situation you are will be use [Remote] attribute for validation model property.

Resources