How to create and use editor template in mvc3 - asp.net-mvc-3

I am new to MVC; I would like to create two editor templates one for readonly textbox and another for editable textbox.
Editable textbox code:
#model string
#Html.TextAreaFor(m=>m,new {size = 35})
Readonly textbox:
#model string
#Html.TextAreaFor(m=>m,new {#readonly = "readonly",size = 35})
But I am not sure how to use them in views, can i give editor template name in views?

You wouldn't actually call these within the View. You would use Html.Editor or Html.EditorFor of course, however, to associate with these, you need to do so within your model.
Model
[UIHint("NameOfYourEditorTemplate")]
public string EditableText { get; set; }
[UIHint("NameOfYourEditorTemplate")]
public string ReadonlyText { get; set; }
Hope this helps.

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

How to select multiple items from dropdown list, save it and again repopulate the dropdown with the selected list?

I am working on an ASP.NET MVC3 project. I am facing issues regarding multiple selection in dropdown.
The problem is, I have to save multiple items in database from a dropdown list and repopulate it.
I have used the class below to represent each list data:
public class IDNameValueTO {
public int ID { get; set; } //Value of the selection Element
public string Name { get; set; } //Name of the selectionElement
public int Value { get; set; } //1 if value is checked and 0 if not
}
My List goes as follows:
public List<IDNameValueTO> tempList = new List<IDNameValueTO>();
ViewBag.SelectedList = tempList;
I am generating the dropdown list as follows:
#Html.DropDownList("SelectedValue", new SelectList(ViewBag.SelectedList, "ID", "Name"))
Now how do I save the multiple selection and display it later on using dropdown?
The default DropDown helper that is provide in asp.net mvc does not support multiselet.
You'll have to create your own custom multiselect dropdown helper.
Here are some links that can help you create you own custom dropdown helper:
http://blogs.msdn.com/b/rickandy/archive/2012/01/30/asp-net-mvc-dropdownlist-multiselect-and-jquery.aspx
http://utsavized.com/chosen-multiselect-dropdown-list-with-asp-net-mvc3/

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)

Reusable editor template with DropDownList for business objects

I'm using MVC3 with Razor views and would like to build reusable DropDownLists for several of my classes, but after much searching I have not found an example that performs exactly how I need it...
For this example I have two classes like this:-
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
}
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
}
I have a working Controller/View for Person. The view has a DropDownListFor control:
#model Person
...
#Html.DropDownListFor(o => o.Group.ID, (ViewData["groups"] as SelectList))
The view uses the Person class directly, not an intermediary model, as I haven't found a compelling reason to abstract one from the other at this stage.
The above works fine... in the controller I grab the value from Group.ID in the Person returned from the view, look it up, and set Person.Group to the result. Works, but not ideal.
I've found a binder here: MVC DropDownList values posted to model aren't bound that will work this out for me, but I haven't got that working yet... as it only really seems useful if I can reuse.
What I'd like to do is have something like this in a template:-
#model Group
#Html.DropDownListFor(o => o.Group.ID, (ViewData["groups"] as SelectList))
And use it in a view like this:-
#Html.EditorFor(o => o.Group)
However the above doesn't seem to work... the above EditorFor line inserts editors for the whole class (e.g. a textbox for Group.Description as well)... instead of inserting a DropDownList with my groups listed
I have the above template in a file called Group.cshtml under Views/Shared/EditorTemplates
If this worked, then whenever a class has a property of type Group, this DropDownList editor would be used by default (or at least if specified by some attribute)
Thanks in advance for any advice provided...
You can create a drop down list user control to handle this. Under your Shared folder create a folder called EditorTemplates and place your user control there. MVC, by convention, looks in the Shared/EditorTemplates for any editor templates. You can override where it looks for the editor templates but I won't go in to that here.
Once you have your user control created, you'll need to decorate the appropriate property with the "UIHint" attribute to tell the engine what editor it should use for that property.
Following would be a sample implementation.
In the Shared/EditorTemplates folder your user control (_GroupsDropDown.cshtml in this case) would look like:
#model Group
#Html.DropDownListFor(o => o.ID, (ViewData["groups"] as SelectList))
Modify the Group property in the Person to add the UIHint attribute as follows:
**[UIHint("_GroupsDropDown")]**
public Group Group { get; set; }
In your controller you would need
ViewData["groups"] = new SelectList(<YourGroupList>, "ID", "Name");
Once you have the above code you can use the EditorFor syntax like you desire.
Hope this helps.

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