I have a view which is rendered by calling an action and I'm passing a view model to it e.g. Vm1 then populating some drop down lists.
On this view, I have a "Filters" section with some text boxes and a "Filter" button and I'd like to call another action passing the values of the text boxes and then rendering the second view partially on the page within a div.
So I have done this and my action looks like below which is called by ajax when the "Filter" button is clicked:
ActionResult ActionName (string inputText1, string inputText2, string inputText3, ...)
Because I have about 10 text boxes, I'd like to create a new c# object and passing that object to this action to look like this which is simpler:
ActionResult ActionName(MyActionFilters myFilters)
How to achieve this?
you can have a model as below
public class MyActionFilters
{
public string Property1{get;set;}
public string Property2{get;set;}
public string[] Property3{get;set;}
// add any number of properties....
}
you can pass the empty model in Get Action method
ActionResult ActionName()
{
MyActionFilters myEmptyActionFilers= new MyActionFilters();
View(myEmptyActionFilers)
}
in the form
Html.TextBoxFor(model => model.Property1)
Html.TextBoxFor(model => model.Property2)
then in the post method you can access the model that is populated in the form
I have removed the previous code. the new code is after the Edit Tag :)
Edit:
Sorry I was not around. This kind of functionality can be achieved easily using AJAX :)
It goes as below.
[HttpPost]
PartialViewResult ActionName(MyActionFilters myActionFilers)// this is magic
{
/*you can access the properties here like myActionFilers.Property1 and pass the
same object after any manipulation. Or if you decided have a model which contains
a variable to hold the search results as well. That is good.*/
return PartialView(myActionFilers);
}
So far this is a good example to refer.
And do not forget to add jquery.unobtrusive-ajax.js script reference to your view. If not Ajax will not affect.In the given example he has done it in the _Layout as you can see.
PS: Choose properties of models that is going to be passed to views, wisely and Enjoy Ajax!!
You need to set the form input names to the properties of your ViewModel, then MVC will do some magic to make For example:
public class FormViewModel {
public string input1 {get;set;}
public string input2 {get;set;}
// and so on
}
then on your Action:
public ActionResult FormPost(FormViewModel model) {
// you'll have access to model.input1, model.input2, etc
}
Lastly, for example, on your HTML Form you'll want to create:
<input type="text" name="input1" />
<input type="text" name="input2" />
or you could use Html.TextBoxFor(model => model.Input1) and the helper will name everything correctly.
The name property of your input tags, should be prefixed by the object name ("MyActionFilters")
for example:
<input type="text" name="MyActionFilters.YOUR_PROPERTY_NAME" />
btw, your action method should be annotated with HttpPost attribute.
[HttpPost]
ActionResult ActionName(MyActionFilters myFilters)
Related
I am fairly new to MVC and had a question about a form I am creating. The page has a form at the top and a grid at the bottom. As people enter data into the form and click the button, the form data is added to the grid below.
My plan is to use a BeginForm and send the form to an HttpPost controller method for processing and then bounce back to the view. Currently, I am using this for the form on the view:
#using (Html.BeginForm("AddRefund", "Refund", FormMethod.Post))
In the controller, I have this:
[HttpPost]
public ActionResult AddRefund(RefundModel refund)
{
if (ModelState.IsValid)
{
(etc...)
My problem is that the "refund" object in controller always arrives from the view empty. From my research, it seems that the model reference in the controller is just there to provide model structure, and NOT to receive the actual model from the view. I don't understand why this is, however, as it would seem very valuable to be able to send a populated viewmodel from the view to a controller.
Also, how would you guys handle the code for this problem? How would you collect all of these form submissions from the user, present them to the user in the grid below the form, and then ultimately submit the page and insert all of the items in the grid into the database?
edit: here is my view
#model RefundsProject.Models.RefundModel
#using (Html.BeginForm("AddRefund", "Refund", FormMethod.Post))
{
(all of the form elements are here)
<input id="button-add" type="submit" value=" Add Refund to List " />
}
Eventually, there will be another button at the very bottom of the view that will submit all of the items the user entered into the grid to the database.
From my research, it seems that the model reference in the controller is just there to provide model structure, and NOT to receive the actual model from the view.
This is completely the opposite of the way ASP.Net MVC was designed. ASP.Net comes with default ModelBinders that are used to Bind data from a Form, Querystring, Ajax (Json and XML) to a strongly typed object for a Controller Method.
My problem is that the "refund" object in controller always arrives from the view empty.
This is most likely due to a lack of knowledge or a misunderstand of how model binders work.
Also, how would you guys handle the code for this problem?
I would Ajax Post the RefundModel back to the controller to validate the refund. If it is valid, then dynamically create fields in the form that will eventually model bind back to an IEnumerable/List on a new method that will then verify all the refunds, one at a time (to validate the data again).
Here is an Extremely broken down example (probably needs some work, but the important parts are there):
Classes:
public class AddRefundsViewModel
{
public RefundModel Refund { get; set; }
}
public class RefundModel
{
public string Reason { get; set; }
public Decimal Amount { get; set; }
}
Methods:
public ActionResult AddRefunds()
{
var model = new AddRefundsViewModel()
model.Refund = new RefundModel();
return this.View(model);
}
[HttpPost]
public ActionResult ValidateRefund(AddRefundsViewModel model)
{
var result = new { isValid = modelState.IsValid };
return this.Json(result);
}
[HttpPost]
public ActionResult ValidateRefunds(IEnumerable<RefundModel> model)
{
var isRefundsValid = true;
foreach (var refund in model)
{
isRefundsValid = TryValidateModel(refund);
if (!isRefundsValid )
break;
}
if (isRefundsValid)
{
}
else
{
// either someone hacked the form or
// logic for refunds changed.
}
}
Views:
#model AddRefundsViewModel
// assuming RefundController
#using (Html.BeginForm("Refund", "ValidateRefunds", FormMethod.Post))
{
#html.EditFor(m => m.Refund.Reason)
#html.EditFor(m => m.Refund.Amount)
<input type="button" id="addRefundButton" name="addRefundButton" value="add"/>
<input type="submit" id="submitRefundButton" name="submitRefundButton" value="submit all"/>
}
<!-- jquery -->
$(document).ready(function()
{
$('#addRefundButton').on('click', function()
{
$.ajax({
url: '/Refund/ValidateRefund',
data: $("addRefundForm").serialize(),
success: function(result)
{
if (result.isValid)
{
// create new hidden imput elements, and grid
$("addRefundForm")[0].reset();
}
else
{
// Refund isn't valid
}
}
});
});
});
From my research, it seems that the model reference in the controller is just there to provide model structure, and NOT to receive the actual model from the view. I don't understand why this is, however, as it would seem very valuable to be able to send a populated viewmodel from the view to a controller.
Your a bit wrong. There is a difference between ViewModel and Domain Model. View Model is a class that you use to process the logic between views and your domain (business).
Then there is Domain Model (in .net) this is usually some data container objects (POCO). This is anemic. Based on DDD there is a little difference.
So what is the best practive?
It is always good to use a ViewModel object to transfer data between your views and controller.
Then in controller you can use a mapper (automapper or valueinjecter) to transform them.
Now you have your domain object that you can process.
Using ViewModels to pass data both up and down between controllers and views is completely acceptable.
To help with your model coming up empty issue, inputs, such as <input id="FirstName" type="text" /> need to have name attributes for the MVC model binder to map what you posted into your RefundModel object. In your View code you shared, you only showed a submit button, so it is unclear if your other elements you expect to get mapped have names or not.
To fix my above example of an input tag, you would do <input id="FirstName" name="FirstName" type="text" /> or use a Razor helper: #Html.TextBoxFor(m => m.FirstName)
I'm working on a school project and I need some help.
I've created a form and I want to get the submitted values from it.
Is it possible to do this without using JavaScript?
And in that case, how do I do it?
Form:
<div id="secondRowInputBox">
<% using (Html.BeginForm("Index","Home",FormMethod.Post))
{%>
<%= Html.TextBox("Id")%> <br />
<%= Html.TextBox("CustomerCode") %><br />
<%= Html.TextBox("Amount") %><br />
<input type="submit" value="Submit customer data" />
<%} %>
</div>
Just create an HttpPost action in your controller accepting the form values as parameters:
[HttpPost]
public ActionResult Index(int id, string customerCode, int amount)
{
// You can change the type of the parameters according to the input in the form.
// Process data.
}
You might want to look into model binding. This allows you to create strongly-typed views and saves you the trouble of creating actions with dozens of parameters.
You have already done half the work, now in home controller make an actionresult
[HttpPost]
public ActionResult Index(int id, string customerCode, int amount)
{
// work here.
}
form post method will call this method, as you have specified it in the begin form parameters.
It will be better if you use a model for passing values and use it in view for form elements
[HttpPost]
public ActionResult Index(ModelName modelinstance)
{
// work here.
}
Sample loginModel
public class LoginModel
{
[Required]
[Display(Name = "Username:")]
public String UserName { get; set; }
[Required]
[Display(Name = "Password:")]
[DataType(DataType.Password)]
public String Password { get; set; }
}
now if was using this login model in the form
then for the controller action, modelinstance is simply the object of model class
[HttpPost]
public ActionResult Index(LoginModel loginDetails)
{
// work here.
}
if you have a lot of variables in the form then having a model helps as you don't need to write for all the properties.
Henk Mollema's answer is good. Here to say something more on it.
Html.TextBox will generate html like below one, there's a name attribute.
<input id="CustomerCode" name="CustomerCode" type="text">
When you submit the form, all the values of input fields can be get from Request.Form by name attribute as key Request.Form["CustomerCode"], and ASP.NET MVC has done some magic for us, so it can simply go into the param of the action method.
view:
#model
#using (Html.BeginForm("action", "Controller"))
{
#html.action("action1","controller1") //use model1
#html.action("action2","controller2") //use model2
#html.action("action3","controller3") //use model3
<button type="submit">submit</button>
}
Parent Model
{
public model model1{get; set;}
public model model2{get; set;}
public model model3{get; set;}
}
controller
[httppost]
public ActionResult Submit(parentmodel abc)
{
}
So my question is when I post the data the parentmodel is return as null but when I try as
[httppost]
public ActionResult Submit(model1 abc)
{
}
I get the form values in model1. Is my approach right? What should be done to get the form values in the parent model?
First of all always mention your model at top.
#model MyMVCModels
#Html.TextBoxFor(m => m.Model1.Name)
Here is the beauty, Model 1 value has to be appropriate while you are setting in your textboxes or controls.
Also the structuring of your Model's might not also be correct.
It's really hard to tell what you're trying to do from your question, but if I understand it correctly, you want to pass your form values to three separate partials simultaneously?
If that's the case, I'd recommend skipping the form postback and just make three ajax calls to load the partials when you click the submit button.
Without customization, can I do something like this in MVC 3?
[HttpGet]
public ViewResult MyAction(ViewModel model)
{
// Do stuff
return View("ViewName", model);
}
The reason I am doing this is to pass data between different pages as part of a work flow. (I.e. when user fnishes what's needed in step 1, pass the form data to step 2...)
It will work as long as you have the same parameter Name as of the Property name of your Model class
Assuming your class is like this
public class ViewModel
{
public string Name { set;get;}
public string Loc{ set;get;}
}
You can do a Get request like this
MyAction?Name=jon&Loc=America
Shyju's answer only works if the members of class in the endpoint's method signature contains only scalar properties. But what if you have nested classes? Let's assume that your ViewModel class looks like this:
public class ViewModel
{
public string Name { get; set; }
public string Title { get; set; }
public Address MyAddress { get; set; }
}
And the Address class looks like this:
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
Now let's say the GET request was done via AJAX and you did something like this in JavaScript:
var address = {
Line1: "123 Nowhere St.",
Line2: "Apt. B5"
}
var getRequestData = {
Name: "Joe",
Title: "Manager",
MyAddress: address
}
var uriString = $.param(getRequestData); //the parameters for the GET request
$.get("/ViewResult?" + uriString, function (data) { /*callback function*/ });
Even though the shape of your address object in JavaScript perfectly matches the C# Address class in the endpoint's method signature, the Line1 and Line2 sub-properties will NOT bind. Their values will come through as null.
There are two workarounds to this.
Workaround 1:
The first is to use dot notation when naming the parameters in the GET request instead of nested JavaScript objects. Using this method, the GET request data in AJAX would look like this:
var getRequestData = {
Name: "Joe",
Title: "Manager",
MyAddress.Line1: "123 Nowhere St.",
MyAddress.Line2: "Apt. B5"
}
MVC model binding will know how to do this, as long as all your property names all match up (they are case-sensitive, so be careful).
If you're not using AJAX, but just a plain HTML form submit, it's even easier. Just name the input elements with that same dot notation. Razor syntax makes this really easy with helper methods like TextBoxFor(), but here's an example in plain HTML:
<form method="get" action="/ViewResult">
<input type="text" name="Name" />
<input type="text" name="Title" />
<input type="text" name="MyAddress.Line1" />
<input type="text" name="MyAddress.Line2" />
<button type="submit">Submit GET request</button>
</form>
Workaround 2:
The other way around this is to simply use a POST request instead of a GET. Beware that it's technically bad practice to perform a POST request without the intent of actually changing some data on the server side, but it is an option.
You can do it; it will automatically bind any values in the query string to properties with matching names.
That said, it's not something that's generally done; it's the [HttpPost] method where you see the model binding performed, as the interfaces for the two actions need to be different somehow. You can solve that by posting back to a different action name, but you may still trigger model validation errors on the (partial) load of the model, which would be really confusing to a user.
For Web API 2:
[HttpGet]
public ActionResult Get([FromUri]ViewModel model)
{
// Do stuff
return View("ViewName", model);
}
You can post a form to a get by setting the PostMethod attribute to get. If the form's input fields match any of the accepting ViewModel then they will be filled. These matches are determined by the name field in an input (<input name="MatchedField"> -> public string MatchedField { get; set; }).
What you should do is pass the form from a post, and then redirect to the get from the post action. This pattern is best practice and is known as the Post-Redirect-Get pattern.
I would advise against this approach. Best solution to just use POST, because if you use GET, once you click back from step 3 to step 2 and the browser cache is not available, you will perform actions on an old version of the ViewModel. Is there a particular reason why you want to use GET?
I can not suggest to use QueryString to pass values.
You can use one of below:
This code will render a partial view with the given model.Be sure you add model to your view. And your view should be placed in Shared folder
public ActionResult myaction(ViewModel model)
{
return PartialView("anotherView", model);
}
Another way to do almost the same thing:
public ActionResult myaction(ViewModel model)
{
return View("someAnotherView", model);
}
if your view is not in the same controller , use the path for view name like "../Controller/viewName"
There is also a different approach which can be done by using TempData:
public ActionResult myaction(ViewModel model)
{
TempData["model"] = model;
return RedirectToAction("someAnotherView");
}
but you should reach your data in the view with the code as shown below:
#{
ViewModel model=(ViewModel)TempData["model"];
}
Hope one of above helps..
Regards
Is it possible from a Controller to show a view, and then dependant on what that user selects in dropDownList - render another different view back in the original calling controller? Kind of a "daisy-chaining" effect.
The thinking behind this - is a user selecting a vehicle type - (associated with an ID number) in a view, back in the Controller dependant on what was chosen will render another view immediately displaying HTML according to the vehicle type they chose e.g. an HTML page for car or a boat or aeroplane etc...
If this is possbile can someone point me to a code examaple?
Actual Database Model below - but it is for documents, not vehicles!
check the method paremetares of your action method and return different views baed on that . Something like this.
public ActionResult GetInfo(string id,string vehicleTypId)
{
if(String.IsNullOrEmpty(vehicleTypeId))
{
var vehicle=GetVehicleType(vehicleTypId);
return View("ShowSpecificVehicle",vehicle) ;
}
var genericVehicle=GetVehicle(id);
return View(genericVehicle);
}
EDIT : Saying so, I seriously think you should keep those in 2 seperate Action methods. That makes your code clean and better readable. You may move the common functionality to a function and call if from bothe the action methods id needed. So i would do it in this way
Assuming you have a ViewModel for the first page( displays all vehicletypes)
public class VehicleTypesViewModel
{
//other relevant properties
public IEnumerable Types { set;get;}
public int SelectedTypeId { set;get;}
}
Your GET request for the initial view will be handled by this action result.It gets all the Vehicle types and return that to your view in the ViewModels Types property.
public ActionResult VehicleTypes()
{
VehicleTypesViewModel objVM=new VehicleTypesViewModel();
objVM.Types=dbContext.VehicleTypes.ToList();
return View(objVM);
}
and in your View called VehicleTypes.cshtml,
#model VehicleTypesViewModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(Model.SelectedTypeId,new SelectList(Model.Types,"Text",Value"),"Select")
<input type="submit" value="Go" />
}
Another Action method to handle the form post. You have the selected type id here and you can get the specific details here and return a different view
[HttpPost]
public ActionResult VehicleTypes(VehicleTypesViewModel model)
{
// you have the selected Id in model.SelectedTypeId property
var specificVehicle=dbContext.Vehicles.Where(x=>x.TypeId=model.SelectedTypeId);
return View("SpecificDetails",specificVehicle);
}
Alternatively you can do a Get request for the specific vehicle using RedirecToAction method. I would prefer this approach as it sticks with the PRG pattern.
[HttpPost]
public ActionResult VehicleTypes(VehicleTypesViewModel model)
{
int typeId=model.SelectedTypeId;
return RedirectToAction("GetVehicle",new {#id=typeId});
}
public ActionResult GetVehicle(int id)
{
var specificVehicle=dbContext.Vehicles.Where(x=>x.TypeIdid);
return View(specificVehicle);
}
With Javascript : You can do a get call to the new view from your javascript also. without the HTTPpost to controller. You should add some javascript in your initial view for that
#model VehicleTypesViewModel
//Include jQuery library reference here
#Html.DropDownListFor(Model.SelectedTypeId,new SelectList(Model.Types,"Text",Value"),"Select")
<script type="text/javascript">
$(function(){
$("#SelectedTypeId").change(){
window.location.href="#Url.Action("GetVehicle","Yourcontroller")"+"/"+$(this).attr("id");
});
});
</script>
I think to get a better user experience create a partial view, and load that partial view in a div in the same page via an ajax call.
public ActionResult GetVehicalInfo(string id, string vehicleType)
{
var vehicle = GetVehicleType(id, vehicleTypId);
return PartialView("vehicle);
}