I want to custom edit filed for KENDO UI grid with date.
I created grid like this:
#(Html.Kendo().Grid<TT.TT.Web.Models.ViewModel.WorkViewModel>()
.Name("gridAdd")
.Columns(columns =>
{
columns.Bound(work =>
work.Date).EditorTemplateName("WorkDate");
})
)
Editor template look like this:
#model DateTime?
#(Html.Kendo().DatePicker()
.Name("WorkDate")
.Value(Model == null ? DateTime.Now.Date : #Model).Format("dd.MM.yyyy")
)
And in TT.TT.Web.Models.ViewModel.WorkViewModel have this property:
[Display(Name = "Datum")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime Date { get; set; }
Everythink works, but when I click to edit date column, the value is always empty. I need to set default value due to value in non edit mode. Thanks!
When i look to DateTime modeli in editor:
#model DateTime?
#Html.Raw(#Model)
The value is always: 01.01.0001 0:00:00 and it should be 11.07.1990
I want to create Html helper method to add title html attribute for each items in DropDownListFor control.
#Html.DropDownListFor(m=> m.StateId, Model.States)
public class Model
{
public int? StateId {get; set;}
public List<SelectListItem> States {get; set;}
}
In controller,
Model m = new Model();
m.States = GetStates(). This will return List<SelectListItem> of States with Value and Text.
Now I want to create html helper method to add title attribute for each item with text value.
You will need to create on your own.
You can pull from similar implementation
Adding html class tag under <option> in Html.DropDownList
Also
give a try to
#Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { #class = "required", title="priority" })
i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?
The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }
Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?
1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl
Ok here is my challenge:
I want to create a dropdownlist with three strings in my Register View - "Please Select", "I am a client", and "I am a vendor". When the user selects the "I am a client" and submits he is added to the "Client" role. When the user selects the "I am a Vendor" role he is added to the "Vendor" role. If the user doesn't select either and leaves on "Please select" validation occurs.
I can get the roles to directly populate via the ViewBag. Here's how:
Register.cshtml -
<div class="editor-label">
#Html.LabelFor(m => m.Role, "I am a:")
</div>
<div class="editor-field">
#Html.DropDownList("Role", ViewBag.Roles as SelectList,"Please Select")
</div>
AccountModel.cs -
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
AccountController.cs -
public ActionResult Register()
{
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList());
return View();
What I still need to accomplish -
Currently the dropdownlist only populates the actual roles. This is not what I want though.
How do I instead create a dropdownlist for three strings in my Register View - "Please Select", "I am a client", and "I am a vendor".
I have no hair left on this one and will be grateful to anyone who can help me to figure this one out. Thanks.
Something similar to below would work perfectly:
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
Then you can have something similar to this in your view.
#Html.DropDownListFor(x => x.Role, new[] {
new SelectListItem() {Text = "I am a vendor", Value = "Vendor"},
new SelectListItem() {Text = "I am a client", Value = "Client"}
}, "Pick a basket")
Edit: String is a reference type and is nullable by default.
You can set the list values in the constructor: SelectList(dataObjects, valueField, textField)
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList(), "Id", "Name");
This allows you to define what attributes of your Role objects are being set as the values and texts of the options.
Here is my model:
public class NewsCategoriesModel {
public int NewsCategoriesID { get; set; }
public string NewsCategoriesName { get; set; }
}
My controller:
public ActionResult NewsEdit(int ID, dms_New dsn) {
dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
var categories = (from b in dc.dms_NewsCategories select b).ToList();
var selectedValue = dsn.NewsCategoriesID;
SelectList ListCategories = new SelectList(categories, "NewsCategoriesID", "NewsCategoriesName",selectedValue);
// ViewBag.NewsCategoriesID = new SelectList(categories as IEnumerable<dms_NewsCategory>, "NewsCategoriesID", "NewsCategoriesName", dsn.NewsCategoriesID);
ViewBag.NewsCategoriesID = ListCategories;
return View(dsn);
}
And then my view:
#Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)
When i run, the DropDownList does not select the value I set.. It is always selecting the first option.
You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:
public class MyViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then populate this view model from the controller:
public ActionResult NewsEdit(int ID, dms_New dsn)
{
var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
var categories = (from b in dc.dms_NewsCategories select b).ToList();
var model = new MyViewModel
{
SelectedCategoryId = dsn.NewsCategoriesID,
Categories = categories.Select(x => new SelectListItem
{
Value = x.NewsCategoriesID.ToString(),
Text = x.NewsCategoriesName
})
};
return View(model);
}
and finally in your view use the strongly typed DropDownListFor helper:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)
just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.
Controller:
ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);
Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)
Then this is my view to render it:
<div class="editor-label">
#Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
#Html.DropDownList("ActionStatusId")
#Html.ValidationMessageFor(model => model.ActionStatusId)
</div>
I think it is pretty simple, I hope this helps! :)
I drilled down the formation of the drop down list instead of using #Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
#foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="#option.Value" #(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>#option.Text</option>
}
</select>
Well its very simple in controller you have somthing like this:
-- Controller
ViewBag.Profile_Id = new SelectList(db.Profiles, "Id", "Name", model.Profile_Id);
--View (Option A)
#Html.DropDownList("Profile_Id")
--View (Option B) --> Send a null value to the list
#Html.DropDownList("Profile_Id", null, "-- Choose --", new { #class = "input-large" })
Replace below line with new updated working code:
#Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)
Now Implement new updated working code:
#Html.DropDownListFor(model => model.NewsCategoriesID, ViewBag.NewsCategoriesID as List<SelectListItem>, new {name = "NewsCategoriesID", id = "NewsCategoriesID" })
I want to put the correct answer in here, just in case others are having this problem like I was. If you hate the ViewBag, fine don't use it, but the real problem with the code in the question is that the same name is being used for both the model property and the selectlist as was pointed out by #RickAndMSFT
Simply changing the name of the DropDownList control should resolve the issue, like so:
#Html.DropDownList("NewsCategoriesSelection", (SelectList)ViewBag.NewsCategoriesID)
It doesn't really have anything to do with using the ViewBag or not using the ViewBag as you can have a name collision with the control regardless.
I prefer the lambda form of the DropDownList helper - see MVC 3 Layout Page, Razor Template, and DropdownList
If you want to use the SelectList, then I think this bug report might assist - http://aspnet.codeplex.com/workitem/4932
code bellow, get from, goes
Controller:
int DefaultId = 1;
ViewBag.Person = db.XXXX
.ToList()
.Select(x => new SelectListItem {
Value = x.Id.ToString(),
Text = x.Name,
Selected = (x.Id == DefaultId)
});
View:
#Html.DropDownList("Person")
Note:
ViewBag.Person and #Html.DropDownList("Person") name should be as in view model
To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");
For anyone that dont want to or dont make sense to use dropdownlistfor, here is how I did it in jQuery with .NET MVC set up.
Front end Javascript -> getting data from model:
var settings = #Html.Raw(Json.Encode(Model.GlobalSetting.NotificationFrequencySettings));
SelectNotificationSettings(settings);
function SelectNotificationSettings(settings) {
$.each(settings, function (i, value) {
$("#" + value.NotificationItemTypeId + " option[value=" + value.NotificationFrequencyTypeId + "]").prop("selected", true);
});
}
In razor html, you going to have few dropdownlist
#Html.DropDownList(NotificationItemTypeEnum.GenerateSubscriptionNotification.ToString,
notificationFrequencyOptions, optionLabel:=DbRes.T("Default", "CommonLabels"),
htmlAttributes:=New With {.class = "form-control notification-item-type", .id = Convert.ToInt32(NotificationItemTypeEnum.GenerateSubscriptionNotification)})
And when page load, you js function is going to set the selected option based on value that's stored in #model.
Cheers.