Correct way to use .NET MVC DropDownList? - c#

I am quite new to MVC, and at the moment I'm developing my first application, and trying to get my head around it. For a while I have tried to find out the best way to use a DropDownList in MVC.
By that I mean, is it possible to modify a model, or viewmodel property in a way that the view that is strongly typed to it is passed a DropDownList with the desired options?
Basically what I am asking is, what is the best way to populate an MVC DropDownList with data from a db and send it to the view?

The list-items in an MVC DropDownList (a <select> element) are provided by any IEnumerable<SelectListItem> which is provided by your ViewModel or optionally through the ViewData, like so:
ViewModel:
public class CustomerViewModel {
public String Title { get; set; }
public IEnumerable<String> ValidTitles { get; set; }
}
Controller action:
[HttpGet]
public ActionResult AddCustomer() {
CustomerViewModel vm = new CustomerViewModel();
vm.Title = "Mr";
vm.ValidTitles = new SelectListItem[] { new SelectListItem("Mr", "Mr"), new SelectListItem("Mrs.", "Mrs."), new SelectListItem("Sgt.", "Sgt.") };
return View( vm );
}
View file (aspx syntax):
<p>Title: <%= Html.DropDownListFor( vm => vm.Title, Model.ValidTitles ) %></p>
So if you read and understand my example, you'll see where you should hit the database.
Remember: the ViewModel is an encapsulation of the entire variable-data state of a view passed to the client.

Basically what I am asking, what is the best way to populate a mvc dropdownlist with data from a db and send it to the view?
It is actually pretty simple,you just need to read the basics of how to use dropdowns in MVC. In a few words:
Create a model for passing it to the view, and let the controller build that model from the data incoming from db.
Create 2 properties in your model for using them in the dropdownlist, (i.e: int selectedItem, SelectListItem items)
Once in your view, note that there are 2 versions of dropdownlist helpers, the strongly typed and non-strongly typed, you should use the strongly typed always you can, it is better and more consistent.

Related

How to pass a strongly typed model and a list of models to a view simultaneously

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.

How to set a value taken from the database to a label in view?

I'm using C# MVC razor to my project. I'm in beginner level in this technology. What I do here is display some details taken from the database. I have decided to use some usual way to display details. Without using keywords like "#Html.LabelFor" I have used the below code.
<label id="SID" name="SID" type="text" class="validate"></label>
Now I expect to display a detail called "SID" in this label. I have created the controller and taken the details also. But I couldn't find how to show details in a label. So please help me with this.
You need to get the data from your db in your action method and pass it to the view where you use it to set the label text. You can use a view model to pass this info or ViewBag or you can simply pass this value if that is the only thing you want to pass.
Here is an example
public ActionResult Index()
{
string myLabelText="Read this from db";
return View((object)myLabelText); // Thanks Stephen for the comments
}
Now in the view which is strongly typed to string
#model string
<label id="SID" name="SID" class="validate">#Model</label>
Usuaully you might want to send more than one item from your view. In such cases, you might consider the view model approach. Create a view model class first.
public class MyPageVm
{
public string MyLabelText { set;get;}
public string MyLabelText2 { set;get;}
}
and in the action
public ActionResult Index()
{
var vm = new MyPageVm();
vm.MyLabelText="Read this from db";
vm.MyLabelText2="Another one to read from db";
return View(vm);
}
Now since we are passing an object of MyPageVm class,we need to make our view strongly typed to that.
#model MyPageVm
<label id="SID" name="SID" class="validate">#Model.MyLabelText</label>
<label id="SID2" name="SID2" class="validate">#Model.MyLabelText2</label>

Interaction between Models and ViewModels in ASP.NET MVC

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

use id from url directly in a view

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
}

ViewData and ViewModel in MVC ASP.NET

I'm new to .Net development, and now are following NerdDinner tutorial. Just wondering if any of you would be able to tell me
What is the differences between ViewData
and ViewModel
(all I know is they are used to pass some form of data from controller to view) and perhaps tell me on what situation should I use ViewData instead of ViewModel and vice versa
Thanks in advance!
Sally
What is ViewData ?
dictionary object that you put data into, which then becomes
available to the view.
ViewData Sample
Controller Action method likes :
public class HomeController : Controller
{
public ActionResult Index()
{
var featuredProduct = new Product
{
Name = "Smart Phone",
QtyOnHand = 12
};
ViewData["FeaturedProduct"] = featuredProduct;
return View();
}
}
How to use ViewData on View ?
#{
var viewDataProduct = ViewData["FeaturedProduct"] as Product;
}
<div>
Today's Featured Product is!
<h3>#viewDataProduct.Name</h3>
</div>
What is a ViewModel ?
Allow you to shape multiple entities from one or more data models or
sources into a single object
Optimized for consumption and rendering by the view
Its like :
How to use ViewModel with MVC 3 ?
Domain Model
public class Product
{
public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public Guid Id { get; set; }
public string ProductName { get; set; }
}
ViewModel
public class ProductViewModel
{
public Guid VmId { get; set; }
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
}
Controller Action Method
[HttpGet]
public ActionResult AddProduct()
{
//for initialize viewmodel
var productViewModel = new ProductViewModel();
//assign values for viewmodel
productViewModel.ProductName = "Smart Phone";
//send viewmodel into UI (View)
return View("AddProduct", productViewModel);
}
View - AddProduct.cshtml
#model YourProject.ViewModels.ProductViewModel //set your viewmodel here
Conclusion
By using ViewModel can pass strongly-typed data into View
But ViewData is Loosely Typed.So Need to cast data on View
ViewModel can use for Complex scenarios such as merging more than one
domain model
But ViewData can be used only for simple scenarios like bring data
for the drop down list
ViewModel can use for attribute-based validation scenarios which
needed for Ui
But Cannot use ViewData for such kind of validations
As a best practices always try to use strongly typed data with
Views.ViewModel is the best candidate for that.
ViewData:
In short, use ViewData as support data, such as a datasource to a SelectList.
ViewModel:
ASP.NET MVC ViewModel Pattern
When a Controller class decides to render an HTML response back to a
client, it is responsible for
explicitly passing to the view
template all of the data needed to
render the response. View templates
should never perform any data
retrieval or application logic – and
should instead limit themselves to
only have rendering code that is
driven off of the model/data passed to
it by the controller.
[...]
When using [the "ViewModel"] pattern we create strongly-typed
classes that are optimized for our
specific view scenarios, and which
expose properties for the dynamic
values/content needed by our view
templates. Our controller classes can
then populate and pass these
view-optimized classes to our view
template to use. This enables
type-safety, compile-time checking,
and editor intellisense within view
templates.

Categories

Resources