Lets say that i have an URL that looks something like this: localhost/userdetails/5 where 5 is the users ID. Is there any way to make use of the ID directly in the view (razor viewengine) and show the details? Or do i handle it in the default action in the controller?
To keep things simple now, focusing on getting the id to the view, you basically want to use the id to populate your model with data and then pass that to the view. So in your controller:
public ActionResult Index(int id)
{
UserModel model = db.Users.Where(u => u.Id == id).SingleOrDefault();
return View(model);
}
The view (very simplified) might look like this:
#model MyProject.Models.UserModel
#Html.DisplayFor(m => m.Id)
#Html.DisplayFor(m => m.Username)
This is very basic though. Eventually, you'll get to a point where you realise you should use viewmodels for your views instead of a domain model that's come directly from the data source. That in itself gives you another problem to solve in the form of mapping properties from the domain model onto your viewmodel. Typically, AutoMapper or ValueInjecter are used for that. For now though, it's probably best to just focus on passing data to a view and getting it back into a controller so that you can do something with it.
Update
This is a simple scenario which demonstrates how to get the data back into the controller. So basically, you'd have a form which you would submit:
#using (Html.BeginForm("Index", "Home"))
{
// Form elements and submit button
}
That would post the data to this action method for you to do whatever you wish with the data:
[HttpPost]
public ActionResult Index(UserModel inputModel)
{
// Check to see if the model's data was valid.
if (ModelState.IsValid)
{
// Do something in the database here.
// Then redirect to give the user some feedback.
return RedirectToAction("Thanks");
}
// The model validation failed so redisplay the view.
return View(inputModel);
}
you can use this in both the controller or in the View as an extension method.
Example: asuming your routes id holder has the default values in global.asax
public int IdFromAdress(HttpContext httpContext)
{
RouteData rd = httpContext.Request.RequestContext.RouteData;
string stringId = (string)rd.Values["id"];
return int.Parse(stringId);
{
You can get the id with this
#HttpContext.Current.Request.RequestContext.RouteData.Values["id"].ToString()
But I would reccomend to use a ViewMdoel to pass the value to the view and not the ViewBag or accessing directly from the view
You should use the model (i.e. the model passed back to your view). A ViewBag is another option but since the ID is part of the model itself, it wouldn't make any sense to do that.
View
#model User
#{
ViewBag.Title = "User Details";
}
#Model.Id;
Controller
public ActionResult UserDetails(int id)
{
return View("UserDetails", (object)id);
}
Yes you can. There is more than one way to do it, but since you've tagged your post MVC, assume you'll want to do it the 'MVC way', which means (imo) using a view model.
So you write a view model
public class MyViewModel()
{
public int ID {get; set;}
}
You populate the model in the controller and pass it to the view
public ActionResut MyView (int id)
{
var viewModel = new MyViewModel {ID = id};
return View (viewModel);
}
Then you have a strongly typed view (strongly typed to the MyViewModel, that is)
and you can reference the model's properties
#Model.ID
Then to make this useful, you can add whatever other properties you're wanting to work with to your view model. Then you can populate them in your controller before rendering the view (to show user info, for example), or let the user populate them for you in the view (using textboxes and such wrapped in a form). Then you can collect the user input in the post action in the controller like so
[HttpPost]
public ActionResult MyView(MyViewModel viewModel)
{
//do stuff with the data from the viewModel
}
Related
My end goal is to pass a strongly typed model (to populate a drop-down menu) and a list of models (based on a search query) to a view simultaneously from a controller. The view I am passing it to is the "Clear()" view. Currently in my HomeController.cs I have:
public ActionResult Clear()
{
var states = GetAllStates();
var model = new ProjectClearanceApp.Models.Project();
model.States = GetSelectListItems(states);
return View(model);
}
private IEnumerable<string> GetAllStates()
{
return new List<string>
{
"AL",
// ... (you get the point)
"WY",
};
}
private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
{
var selectList = new List<SelectListItem>();
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element,
Text = element
});
}
return selectList;
}
I read somewhere that that's the best way to get the list of options for a drop-down menu. Now I'd also like a pass a LIST of models to the same view (Clear.cshtml) based on a search query. I'm reading from this Microsoft tutorial to search in the controller action for that view by adding
public ActionResult Index(string searchString)
{
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);
}
to the controller. How can I pass both the list of drop-down options AND the list of models that fit the search from the controller to the view (or, how can I achieve the same effect without passing both from the controller)?
To achieve your end goal ,that is passing the list of model, viewmodel will be the best solution as per my knowledge.
Some key note above view model:
The ViewModel class, which is the bridge between the view and the model. Each View class has a corresponding ViewModel class. The ViewModel retrieves data from the Model and manipulates it into the format required by the View. It notifies the View if the underlying data in the model is changed, and it updates the data in the Model in response to UI events from the View
The ViewModel class determines whether a user action requires modification of the data in the Model, and acts on the Model if required. For example, if a user presses a button to update the inventory quantity for a part, the View simply notifies the ViewModel that this event occurred. The ViewModel retrieves the new inventory amount from the View and updates the Model. This decouples the View from the Model, and consolidates the business logic into the ViewModel and the Model where it can be tested.
Official definition/ Source: https://msdn.microsoft.com/en-us/library/ff798384.aspx
Additional information with Ex:
http://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc
Kindly let me know your thoughts or feedbacks
Thanks
Karthik
Model is a term that really describes what data is meant to be bound to the view, and what data the model binder will handle when you make a request to/from the view. Because I'm not exactly sure how you are using Index and Clear, I'll just stub these out generally. Please let me know if I've missed the point of your question:
If you are having trouble passing, for example, List<Movies> movieModel along with your List<SelectListItem> selectedStates (or any additional values) to the view, here are 2 common ways to do this.
ViewModel approach -- Create a model class that contains your "main" model along with any other properties, lists, etc. that you'll need in the view.
eg:
public Class MyViewModelClass
{
List<Movie> MoviesList {get;set;}
List<SelectListItem> StatesList {get;set;}
//some other properties/methods can go here as well ...
}
//In Controller
{
MyViewModelClass model = new MyViewModelClass();
model.StatesList = <build your select list>;
model.MovieList = <build your movie list>;
return View(model);
}
In the controller you would then create a new instance of MyViewModelClass model (different name obviously), and populate your movie list, state list, and any other properties, assign them to the model properties, and pass the whole thing as your return View(model);
This is nice because all of the data getting passed to the view can be in one place.
ViewBag approach -- Stick with a single model or List, and pass view-related data (such as dropdown lists, or state bools) in the ViewData or ViewBag.
ex.
//From Controller
public ActionResult SomeMethod()
{
var states = GetAllStates();
var model = <enter movies query here>;
ViewBag.StatesList = GetSelectListItems(states);
//This will be accessible in the view now
return View(model);
}
//In View:
#{
List<SelectListItem> StatesList = (List<SelectListItem>)ViewBag.StatesList; // Can now use this variable to bind to DropDownList, etc.
}
I prefer, for the most part, using a ViewModel to add everything I need. For one, the ViewBag/ViewData requires some casting, and it relies on "magic strings", so you don't have Visual Studio letting you know if you'd typed something wrong with intellisense. That said, either is viable.
Could you explain the interaction Models and ViewModels in the ASP.NET MVC?
If I need to display data on the page, but not edit, whether to create a ViewModel to display or use the Model?
I have two methods in the repository. One returns the Model and the other Model gets.In View I need to send the model. Should I convert the resulting Model to a ViewModel that would pass it to the View, and upon receipt of the submission to convert it back into the model to keep it?
For example I have a class model and class ViewModel.
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
public class EditItemItemViewModel
{
public string Name { get; set; }
public int Price { get; set; }
}
On the edit page, I clicked the edit item, and must get to the controller:
[HttpGet]
public ActionResult EditItem(int id)
{
//some code
return View();
}
Where can I get the ID if I passed in the view ViewModel in which there was no ID?
If I somehow got the ID, I need to do the following, which would save the model?
[HttpPost]
public ActionResult EditItem(EditItemItemViewModel ViewModel)
{
var Item = _dataManager.Items.GetItemById("1");
Item.Name = ViewModel.Name;
Item.Price = ViewModel.Price;
_dataManager.Items.AddItem(Item);
return View("Sucsess");
}
Could you tell me how to work with Models and ViewModels?
You can get the id a few different ways:
#Html.HiddenFor(m => m.Id)
This will include the property in the actual HTTP request.
Another option is to simply include the id as part of your route (this is what I usually do):
#Html.BeginForm("EditItem", "SomeController", new { Id = Model.Id }, FormMethod.Post) {
...
}
In both instances, make sure to validate that the user should be able to update the record that corresponds to that id! There's nothing stopping a user from tampering with the id and sending you a different value.
As for whether or not to display the database model or the view model, that's really up to you. I would always advocate building a view model and keep your database models out of the picture except for in your controller. The convention I use at work is for every database object that I need to send to users I will create a corresponding view model. So if I have a database object called Product I will build another class for the view called ProductModel.
An advantage of following that pattern is something I actually explained to another user earlier in regards to model binding.
If I need to display data on the page, but not edit, whether to create a ViewModel to display or use the Model?
If it's very simple (like your example) and the properties map 1-1 like they do now. I would just use the Model as a view model, it's easier. Though if you want you could create a view model with the exact same properties and populate that and display it..it's a bit more work, but makes it so your domain models aren't necessarily tied to your views.
If you do that you may want to look into something like AutoMapper which would allow you to do something like
//simply copies the properties from one type to another
var viewModel = Mapper.Map<Item, EditItemItemViewModel>();
I have two methods in the repository. One returns the Model and the other Model gets.In View I need to send the model. Should I convert the resulting Model to a ViewModel that would pass it to the View, and upon receipt of the submission to convert it back into the model to keep it?
If you go the view model route then yes, you will end up doing a lot of converting between model and viewmodel, that's where something like AutoMapper can help out, or you can just create a couple extension methods that convert between the two types.
It looks like Justin Helgerson's answer explaining a way to handle models/viewmodels is pretty good.
Your posting your viewmodel, so i'm going to assume that you've referenced your model within the page
#model MyNameSpace.EditItemItemViewModel
Is there a reason the id is not included in your view model? The easiest method would be to include that in the model and pass the instantiated model when creating the view.
[HttpGet]
public ActionResult EditItem(int id)
{
var myViewModel = new EditItemItemViewModel() { Id = id };
return View(myViewModel);
}
Like Justin said, it is easier to put it in a hidden field somewhere inside the #Html.BeginForm as the id should just be for reference.
[HttpPost]
public ActionResult EditItem(EditItemItemViewModel viewModel)
{
var Item = _dataManager.Items.GetItemById(viewModel.Id);
Item.Name = viewModel.Name;
Item.Price = viewModel.Price;
// Should this be an Add?
_dataManager.Items.AddItem(Item);
return View("Success");
}
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.
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);
}
I have a form using Html.BeginForm() on a view. I have in the controller an ActionResult to handle the post. What I need is to just kick back the results to a view. I can kick off the new view, but I don't know how to pass the data to it and once there I don't know how to display it. Here's what I have in the ActionResult.
[HttpPost]
public ActionResult Index(FormCollection collection)
{
ViewBag.Title = "Confirm your order";
return View("OrderConfirmation", collection);
}
If I just do a return View("OrderConfirmation"); it will go to the view so I know I got that working. I just don't know how to pass the data. Right now I have it strongly typed to the same model the form was which causes errors because this FormCollection is not the same obviously. If I remove the strongly typed line the above works, but I have no idea how to loop through the collection at that point.
Thanks for the help.
Use a ViewModel and a stongly typed view. Then you can pass the model to the second view.
public ActionResult Index(Order order)
{
return View("OrderConfirmation", order);
}
ASP.NET MVC will automatically create an order instance and fill the properties from the posted FormCollection.
First don't use FormsCollection, its too generic. You only need it if you need to unit test and access UpdateModel().
Bind to a model type or bind to params:
public ActionResult Index(SomeModel model)
{
return View("OrderConfirmation", model);
}
or
public ActionResult Index(int key)
{
SomeModel model = new SomeModel();
UpdateModel(model);
return View("OrderConfirmation", model);
}
in your view at the top specify
#model MyAppNameSpace.ViewModels.SomeModel