Binding dynamic data to kendo Dropdownlist - asp.net-mvc-3

I am trying to bind a kendo dropdownlist with the model but I am getting undefined in each option.
Model:
public SelectList CountriesTemp { get; set; }
public int Country{get;set;}
Controller:
public ActionResult Registration()
{
RegistrationModel Model = new RegistrationModel();
Model.CountriesTemp = new SelectList(ObjService.GetCountries(), "CountryID", "Country_Name");
return View(Model);
}
View Page
#(Html.Kendo().DropDownListFor(m => m.Country)
//The name of the dropdownlist is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("Country_Name") //Specifies which property of the Product to be used by the dropdownlist as a text.
.DataValueField("CountryID") //Specifies which property of the Product to be used by the dropdownlist as a value.
.BindTo(Model.CountriesTemp ) //Pass the list of Products to the dropdownlist.
)
Can somebody please guide me where I am wrong because if I bind a simple dropdownlist of MVC , It works well. Just one line change as below in ViewPage and it's Working.
#Html.Dropdownlist("CountriesTemp")

It looks like you've got a conflict (so-to-speak going on here). Try something like this:
#(Html.Kendo().DropDownListFor(m => m.Country)
.DataTextField("Text")
.DataValueField("Value") // These may be optional now
.BindTo(Model.CountriesTemp))
Alternatively, you can not use a SelectList and do a property like IEnumerable<Country> Countries { get; set; } on your Model. Then the binding would look something like:
#(Html.Kendo().DropDownListFor(m => m.Country)
.DataTextField("Country_Name")
.DataValueField("CountryID")
.BindTo(Model.Countries))

Related

How to return result to a partial view with kendo grid and kendo textboxes

I'm having a problem in returning values to my view for kendo grid & fields.
Earlier I had only kendo grid in my partial view and hence I used below code to return the values of my grid:
public virtual ActionResult GetValues(long Id1, [DataSourceRequest]DataSourceRequest request)
{
return Json(ViewModel.List<Another_View_Model>.ToDataSourceResult(request));
}
My View Model structure is as follows
ViewModel
{
public long Id { get; set; }
public List<Another_View_Model> Another_View_Model { get; set; }
}
But now, I'm adding kendo textboxes, checkboxes to the same partial view and would like to return server values to those fields too while returning grid values.
My View Model structure is as follows
ViewModel
{
public long Id { get; set; }
public List<Another_View_Model> Another_View_Model { get; set; }
public string textboxField { get; set; }
}
In my controller, I'm doing the following changes but my textbox field values are not returning to the view.
public virtual PartialViewResult GetValues(long Id1)
{
return PartialView("_PartialView", ViewModel);
}
Can anyone please point me where I'm doing wrong or is there a better wayto return result for both grid & kendo elements at the same time within the same model.
My view structure is as follows:
#model ViewModel
#(Html.Kendo().TextBoxFor(p => p.textboxField)
.Name("TextBox")
)
#(Html.Kendo().Grid<Another_View_Model>()
.Name("KendoGrid")
Any help with this is appreciated. Thanks in advance!!
Use either TextBoxFor(p => p.PropertyName) or TextBox().Name("PropertyName") DO NOT use both. The name property will override the TextBoxFor. So in your example, your Kendo Textbox is actually binding to a Property named TextBox instead of textboxField like you were expecting.
The inverse is also true, if you were posting a form, the Model's textboxField will be null, while if you had a string parameter named TextBox it will be populated with the textbox's value

MVC dropdownlist , data not displaying when model is not Ienumerable

I am having a problem passing to the View a Model that contains the dropdown data and the model.
With this code my page loads, but the dropdownlist contains "System.Web.MVC.SelectList" when selected.
Here's my controller code.
public ActionResult Index(string productNameFilter, string productCategoryFilter, String productTypeFilter )
{
var ddl = new Items();
ddl.CategoryddList = itemsRepository.GetItemDdl("Item Categories").Select(c => new SelectListItem
{
Value = c.DropdownID.ToString(),
Text = c.DropdownText
});
ViewBag.CategoryDD = new SelectList(ddl.CategoryddList, "Value", "Text");
var model = itemsRepository.GetItemByName(productNameFilter);
return View(model);
}
Here's my view
#model Ienumerable<Models.items.items>
#Html.DropDownList("productCategoryFilter",
new SelectList(ViewBag.CategoryDD),
"---Select Category---")
Side note - if you use a ViewModel between the View and the Model instead of binding directly to the model, you can put your SelectList on the ViewModel and use #Html.DropdownFor() instead of #Html.Dropdown(). The ViewBag should really be used sparingly.
However back to your original question:
What is "Items()"? in your line
var ddl = new Items();
I'm not sure what good reason you would have NOT to make it enumerable.
I suspect it is not working because you are making a selectlist from a select list twice --
in your code behind you are defining ViewBag.CategoryDD as a SelectList(), and then in your Razor code you are creating a new SelectList() from the existing selectlist. You shouldn't have to do this.
The way I would do this is create a ProductViewModel class that contains your product category list AND your list of products (your current model), and a property for the selected filter.
public class ProductViewModel
{
public IEnumerable<Model.items.items> ProductList {get;set;}
public IEnumerable<SelectListItem> ProductCategoryList {get;set;} //SelectList is an IEnumerable<SelectListItem>
public string SelectedCategory {get;set;}
}
Then on your view the model would be
#model ProductViewModel
#Html.DisplayFor(model => model.SelectedCategory, "---Select Category---")
#Html.DropdownListFor(model => model.SelectedCategory, Model.ProductCatgoryList)

Best way to bind the constant values into view (MVC3)

I have a constants values such as "Required","Optional", and "Hidden". I want this to bind in the dropdownlist. So far on what I've done is the below code, this is coded in the view. What is the best way to bind the constant values to the dropdownlist? I want to implement this in the controller and call it in the view.
#{
var dropdownList = new List<KeyValuePair<int, string>> { new KeyValuePair<int, string>(0, "Required"), new KeyValuePair<int, string>(1, "Optional"), new KeyValuePair<int, string>(2, "Hidden") };
var selectList = new SelectList(dropdownList, "key", "value", 0);
}
Bind the selectList in the Dropdownlist
#Html.DropDownListFor(model => model.EM_ReqTitle, selectList)
Judging by the property EM_RegTitle I'm guessing that the model you're using is auto-generated from a database in some way. Maybe Entity Framework? If this is the case, then you should be able to create a partial class in the same namespace as your ORM/Entity Framework entities and add extra properties. Something like:
public partial class MyModel
{
public SelectList MyConstantValues { get; set; }
}
You can then pass your SelectList with the rest of the model.
There are usually hangups from using ORM/EF entities through every layer in your MVC app and although it looks easy in code examples online, I would recommend creating your own View Model classes and using something like AutoMapper to fill these views. This way you're only passing the data that the views need and you avoid passing the DB row, which could contain other sensitive information that you do not want the user to view or change.
You can also move the logic to generate your static value Select Lists into your domain model, or into a service class to help keep reduce the amount of code and clutter in the controllers.
Hope this helps you in some way!
Example...
Your View Model (put this in your "Model" dir):
public class MyViewModel
{
public SelectList RegTitleSelectList { get; set; }
public int RegTitle { get; set; }
}
Your Controller (goes in the "Controllers" dir):
public class SimpleController : Controller
{
MyViewModel model = new MyViewModel();
model.RegTitle = myEfModelLoadedFromTheDb.EM_RegTitle;
model.RegTitleSelectList = // Code goes here to populate the select list.
return View(model);
}
Now right click the SimpleController class name in your editor and select "Add View...".
Create a new view, tick strongly typed and select your MyViewModel class as the model class.
Now edit the view and do something similar to what you were doing earlier in your code. You'll notice there should now be a #model line at the top of your view. This indicates that your view is a strongly typed view and uses the MyViewModel model.
If you get stuck, there are plenty of examples online to getting to basics with MVC and Strongly Typed Views.
You would prefer view model and populate it with data in controller.
class MyViewModel
{
public string ReqTitle { get; set; }
public SelectList SelectListItems { get; set; }
}
Then you can use:
#Html.DropDownListFor(model => model.EM_ReqTitle, model.SelectListItems)

Binding DropdownList and maintain after postback

I am using MVC3. I'm binding the dropdown with the Data coming from a service. But after the page posts back and a filter applies to list, the dropdown shows the filter record value in the grid because I always bind the list coming from the service.
However, I want the dropdown to always show all the Records in the database.
I don't understand your question that clearly. But it seems that it is a dropdown that you have on your view? I also have no idea what you are trying to bind so I created my own, but have a look at my code and modify it to fit in with your scenario.
In your view:
#model YourProject.ViewModels.YourViewModel
On the view there is a list of banks in a dropdown list.
Your banks dropdown:
<td><b>Bank:</b></td>
<td>
#Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.BankId)
</td>
Your view model that will be returned to the view:
public class YourViewModel
{
// Partial class
public int BankId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
}
Your create action method:
public ActionResult Create()
{
YourViewModel viewModel = new YourViewModel
{
// Get all the banks from the database
Banks = bankService.FindAll().Where(x => x.IsActive)
}
// Return the view model to the view
// Always use a view model for your data
return View(viewModel);
}
[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
if (!ModelState.IsValid)
{
// If there is an error, rebind the dropdown.
// The item that was selected will still be there.
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
return View(viewModel);
}
// If you browse the values of viewModel you will see that BankId will have the
// value (unique identifier of bank) already set. Now that you have this value
// you can do with it whatever you like.
}
Your bank class:
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
This is simple as it gets. I hope this helps :)
PS: Please remember with future posts, always give as much detail as possible so that we can help you better. Also don't forget to display code samples so that we can see what you have already done. The more details that we can have the better.
When you post the model back to the create[Http Post] action is it not possible to have the list of dropdown list values for the banks binded back to the model. I see that if the model is invalid, you call the code
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
to get a list of all the banks again which I assume you need to hit the database again.
Thanks

How do you call UpdateModel when you use a ViewModel class?

In MVC3, it seems that the default way to show properties of a model in your view is like so:
#Html.DisplayFor(model => model.Title)
This works fine if your model matches your object exactly. But if you define a custom ViewModel, for example like in the NerdDinner tutorial
public class DinnerFormViewModel {
// Properties
public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }
// Constructor
public DinnerFormViewModel(Dinner dinner) {
Dinner = dinner;
Countries = new SelectList(PhoneValidator.AllCountries, dinner.Country);
}
}
Then your DisplayFor code would look like:
#Html.DisplayFor(model => model.Dinner.Title)
Which means the names of the form items are Dinner.Title instead of just Title, so if you call UpdateModel in your Action code, MVC won't "see" the properties it needs to see to update your Dinner class.
Is there a standard way of dealing with ViewModels that I'm overlooking for this scenario in MVC3?
Use the 'prefix' parameter for UpdateModel method
UpdateModel(model.Dinner, "Dinner");
and if you need to update a specified properties only - use something like this
UpdateModel(model.Dinner, "Dinner", new []{"Title"});

Resources