I need to have 2 models in my View. But since we could only add 1 view, i took the following approach;
#model Tuple<My.Models.Mod1,My.Models.Mod2>
#Html.DropDownListFor(m => m.Item2.humanKind,Model.Item2.allHuman)
#Html.TextBoxFor(m => m.Item1.food)
But, what i end up getting is the following error;
The model item passed into the dictionary is of type 'My.Models.Mod2', but this dictionary requires a model item of type 'System.Tuple`2[My.Models.Mod1,My.Models.Mod2]'.
What is this, and how can i solve this?
UPDATE
public ActionResult Index()
{
var model2 = new Mod2 { allHuman = allHumans() };
var model1 = new Mod1(); // JUST NOW I ADDED THIS, BUT IT DOESn't WORK
return View(model1,model2);
}
You can only have one model per view. You need to instantiate the Tuple as Ufuk suggested.
However I would suggest creating a new model that has the other models as a property.
The view in question is being called from a controller action that only passes in a My.Models.Mod2 rather than a Tuple<My.Models.Mod1,My.Models.Mod2>.
Double-check the specific controller action that calls this view.
UPDATE
Your controller code
return View(model1,model2);
should be
return View(new Tuple<My.Models.Mod1,My.Models.Mod2>(model1, model2>);
You are passing model1 and model2 as separate parameters rather than as a Tuple.
Build a view model that contains both:
Public class CompositeViewModel{
Public Mod1 mod1 {get;set;}
Public Mod2 mod2 {get;set}
}
Then construct and pass CompositeViewModel to view. Set views to use CompositeViewModel as the model #model CompositeViewModel
Using a Tuple doesn't easily allow you to expand or change what you are doing.
It maybe even looks like you have one ViewModel that has data, and then some associated IEnumerable<SelectListItem>. If that is the case then name the ViewModel like CreateAnimalTypeViewModel which contains all the properties you need to create it, then have various select lists.
If you need to map from something to the ViewModel e.g. if you were doing an edit of an existing item you could use AutoMapper.
You are not creating a tuple instance before sending it to the view.
public ActionResult Index()
{
var model2 = new Mod2 { allHuman = allHumans() };
var model1 = new Mod1();
return View(new Tuple<Mod1,Mod2>(model1,model2));
}
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.
I am new in MVC. I have a view that contains many dropdowns and viewmodel with many lists. Most of these lists are static so I want to cache retrived records. I can do this with (custom) Model binders, but I dont like that to actually use (custom) Model Binder I need to add parameter for every object in Action method like this:
public ViewResult SubmitNewValue(MyViewModel viewMod, IEnumerable<List1> list1, IEnumerable<List2> list2, IEnumerable<List3> list3 ...)
{
viewMod._list1 = list1;
viewmod._list2 = list2;
viewMod._list3 = list3;
...
return View(viewMod);
}
What I think would look better is something like:
public ViewResult SubmitNewValue(MyViewModel viewMod)
{
viewMod._list1 = ModelBinders.GetInstanceFor<List1>();
viewmod._list2 = ModelBinders.GetInstanceFor<List2>();
viewMod._list3 = ModelBinders.GetInstanceFor<List3>();
//I am able to wrap above to separate function like PrepareViewModel(viewMod)
...
return View(viewMod);
}
Is there a function/way to do this?
I am also not sure if I chose good approach but my viewmodel is losing lists for dropdowns, so I need to somehow readd them to ViewModel after [HttpPost] for example.
The modelbinder's sole job is to bind data from the request (querystring or post body) to parameters on your action method. So, no, if there's no parameter, the modelbinder does nothing with the data.
You can access the data directly from the request, i.e. Request["list1"]. However, that's the raw data as the modelbinder would receive it, before it actually did any of the work it does. In other words, you would need to manually do type-coercion or new up things, etc., with that data.
That said, this sounds like an XY problem. What is it that you're actually trying to achieve, because there's probably a better way.
You can use the ControllerBase.ViewBag Property to store resources for the view to use.
public class MyController : Controller {
public ActionResult SubmitNewValue() {
populateDropDownLists();
MyViewModel model = GetDefaultViewModel();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitNewValue(MyViewModel viewMod) {
processMyViewModel(viewMod);
populateDropDownLists();
return View(viewMod);
}
void populateDropDownLists() {
//These could be cached lists
ViewBag.List1 = GetList1();
ViewBag.List2 = GetList1();
ViewBag.List3 = GetList1();
}
}
And then in your view you can access the lists to populate your dropdowns
#Html.DropDownListFor(m => m.MyViewModelProperty, (IEnumerable<SelectListItem>)ViewBag.List1, "Select...", new { #class = "form-control select" })
The view model should not be responsible for storing the lists. Since the lists are only for populating the dropdowns in the view then they should be seperated out
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");
}
I am passing an object (a List) into a view like so:
private readonly CarsContext _db = new CarsContext();
public ActionResult Index()
{
ViewBag.Message = "Foobar";
var result = from cars in _db.CarProfiles
where cars.CarOfTheWeek
select cars;
return View(result.ToList());
}
How do I access this object from within my Index view? I am thinking I need to add it to my dynamic viewbag, and access it that way instead of passing it as an argument, is this correct or if I keep my controller code above as it is, can I access this object from within the view?
Thanks
Make your view strongly typed to the class/ type you are returning to, from your action method.
In your case you are returning a List of CarProfile class objects. So in your view(index.cshtml), drop this as the first line.
#model List<CarProfile>
Now you can access the list of CarProfile using the keyword Model.for example, you want to show all items in the list, in a loop, you can do like this
#model List<CarProfile>
#foreach(var item in CarProfile)
{
<h2>#item.Name</h2>
}
Assuming Name is a property of CarProfile class.
In your Index.cshtml view, your first line would be:
#model YOUR_OBJECT_TYPE
So for example, if you pass a string in your line:
return View("hello world");
Then your first line in Index.cshtml would be:
#model String
In your case, your first line in Index.cshtml would be:
#model List<CarProfile>
This way, if you type #Model in your Index.cshtml view, you could access to all the properties of your list of CarProfile. #Model[0] would return your first CarProfile in your list.
Just a tip, the ViewBag shouldn't be used most of the time. Instead, you should create a ViewModel and return it to your view. If you want to read about ViewModels, here's a link: http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3fundamentals_topic7.aspx
You can access the object in your view by passing it in ViewBag ( The way that you have wrote your controller ). But I think, it is usually better to have a ViewModel and pass data to view, via that ViewModel.
Passing Business objects directly to model ( the way you have done ), make model dependent to business object, that it is not optimal in the most cases. Also having ViewModel instead of using ViewBag has the advantage of using StrongTypes.
private readonly CarsContext _db = new CarsContext();
public ActionResult Index()
{
var result = from cars in _db.CarProfiles
where cars.CarOfTheWeek
select cars;
MyViewModel myViewModel = new MyViewModel( );
myViewModel.Message = "Foobar";
myViewModel.ResultList = result.ToList();
return View( myViewModel );
}
I am developing an asp.net mvc web app in which I want to send 2 objects to View through Controller now I am sending only one object to view through controller
return View(repository.func(id));
and in view I am getting
<% var data = Model.First %>
But now I am confused how to send 2 objects and how to get it.
An excellent occasion to (learn to) use a ViewModel:
class MyViewModel { ... }
// and in the Action:
var view = new MyViewModel();
view.First = repository.func(id) ;
view.Second = ....;
return View(view);
You can use ViewBag (Personally I don't like this approach) or create class which will hold both values and use it for model for your view
I assume your view is strongly-typed to be of the same type as whatever you're returning from:
repository.func(id)
lets say object 'Foo'
Assuming you are using a strongly-typed view:
#model Foo
You can change this to be:
#model IEnumerable<Foo>
Then, your view will be strongly-typed to a collection (IEnumerable) of Foo
and in your view you can do:
foreach(var foo in Model)
{
//Do stuff
}
Naturally, your repository method will have to return a collection of objects (via something that implements IEnumerable - List<> for example)
Just a slight elaboration of Henk's answer
class MyViewModel {
TMyEntityType1 First { get; set; }
IQueryable<TMyEntityType2> Second { get; set; }
}
And then in the action you collect your 2 sets of data and house it in an instance of MyViewModel
var viewModel = new MyViewModel();
viewModel.First = repository.func(id);
viewModel.Second = repository.containing("?");
return View(viewModel);
An in your view you may want to change it to:
<% var dataFirst = Model.First;
var dataSecond = Model.Second;%>
Where Model is now of type MyViewModel and not the return type of repository.func(id)