Add class in dropdown list - asp.net-mvc

#Html.DropDownListFor(m => m.Baled, new SelectList(new [] {"Select Type","Option1", "Option2", "Option3"}))
I want to add a css class in the dropdown list.
I have tried this
#Html.DropDownListFor(m => m.Baled, new SelectList(new [] {"Select Type","Option1", "Option2", "Option3"}, new {#class="myclass"}))
But it doesn't work
If anyone can suggest me any other better way to display dropdown list will be ok too.

You have close the bracket at wrong place. you have defined attribute in second paramter of selectlist. actually it should be close first and define in the last parameter of Html.DropDownListFor
#Html.DropDownListFor(m => m.Baled, new SelectList(new[] { "Select Type", "Option1", "Option2", "Option3" }), new { #class = "myclass" })

Related

Telerik MVC Grid Popup Default Values

I have a Telerik MVC Grid with a custom editable popup template
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.Window(w => w.Width(600))
.TemplateName("Inspection")
)
The template is based on a model, and contains two drop down lists
#(Html.Kendo().DropDownListFor(model => model.InspectionStatus)
.BindTo(new List<SelectListItem>()
{
new SelectListItem() { Text = "Fail", Value = "0" },
new SelectListItem() { Text = "Pass", Value = "1" }
})
)
and
#(Html.Kendo().DropDownListFor(model => model.CloseoutStatusID)
.DataValueField("LookUpID")
.DataTextField("LookUpText")
.DataSource(source => {
source.Read(read => { read.Action("Get", "LookUp", new { LookUp = "CloseOutStatus" }); });
})
)
I need to set the default values for both fields... Currently they both come back as 0 regardless of what I have done.
So far I've:
Tried setting the default value attribute
Set the values in the model's constructor
Set the .Value() to what the default should be.
Everything else is working correctly... I can select a bound item and it returns the correct value. I can edit an existing item and it shows the proper data in the template. I can saved edited data and it returns the correct value.
Any reliable documentation would be greatly appreciated.
Received the answer on the telerik forums.
The telerik grid create action in the toolbar uses the model information in the data source.
by adding the fields to the model and setting the default value there I was able to get the desired behavior.
.Model(model => {
model.Id(Inspection => Inspection.DEPInspectionsID);
model.Field(Inspection => Inspection.CloseoutStatusID).DefaultValue(2);
model.Field(Inspection => Inspection.InspectionStatus).DefaultValue(1);
})

Razor input element custom attribute

Hi I need to do the following:
#Html.TextBoxFor(m => m.Login,
new {
#class = "form-control",
#placeholder = "Username",
required="true" data-required-message="Please insert your name"
})
But Im getting error on data-required-message seems that I can't use "-".
Any clue?
You have to use it with underscore _ and razor will render it as - in html:
data_required_message="Please insert your name"
another thing to note is that you don't need to put # sign in front of every parameter of htmlAttributes , we put it for class becasue class is a reserved word in c#, so it cannot be used directly as a variable name.
your final code will be like:
#Html.TextBoxFor(m => m.Login,
htmlAttributes: new {
#class = "form-control",
placeholder = "Username",
required="true",
data_required_message="Please insert your name"
})
you are also missing a comma after placeholder attribute.
Try data_required_message instead of data-required-message

Possible to change LabelFor?

Say if I have this textbox
#Html.TextBoxFor(x => x.Name, new {id = "add-name", data_parsley_maxlength = "1" })
How do I write my LabelFor so that it references "add-name"?
Or do I have to use #Html.Label?

Multiselect list in Kendo Grid inline editing

I need to use multiselect list in kendo grid (inline editing) so that user can select multiple values from the list per row.
Following are my requirements:
At the time of display, kendo grid should show comma separated list of all the selected values.
At the time of Add, kendo grid should show multiselect list and allow to select multiple values.
At the time of Edit, kendo grid should show multiselect list with already selected values. User should be able to modify the select and add/remove items from the list.
When user clicks on update/save button, selected values from multiselect list should be available in code behind (in update ajax action) along with id of row.
Following what I do as of now:
I am taking an approach similar to using a drop down list in kendo inline grid.
I have created an Editor Template for displaying multiselect at the time of add/edit.
Following is the code:
#model List<Namespace.CompanyConnector>
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelectFor(c=>c)
.Name("company_connector_id")
.DataTextField("connector_name")
.DataValueField("company_connector_id")
.Placeholder("Select connector...")
.AutoBind(false)
.Value((List<int>)ViewData["SelectedValues"])
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCompanyConnectors", "BrandConnector");
})
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
Explanation: I bind a list of model class to the multiselect and set data source in the read action. For selecting the selected values at the time of edit, I have created a function that returns the ids of selected values and put that in View Data in the read action.
I've used this Editor template in my Index page as following code:
#{Html.Kendo().Grid<Cee.DomainObjects.DomainObjects.BrandConnector>()
.Name("BrandConnectorGrid")
.Filterable()
.Events(e => e.Edit("onEdit"))
.DataSource(dataSource => dataSource
.Ajax()
.Events(e => e.Error("error_handler").RequestEnd("onRequestEnd"))
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.brand_id);
model.Field(e => e.CompanyConnectorList).DefaultValue(new
List<Cee.DomainObjects.DomainObjects.CompanyConnector>());
})
.Read(read => read.Action("_AjaxBinding", "BrandConnector",new{companyID = 0 }).Type(HttpVerbs.Post))
.Update(update => update.Action("_UpdateBinding", "BrandConnector").Type(HttpVerbs.Post)))
.Columns(columns =>
{
columns.Bound(c => c.brand_connector_id).Width(0).Hidden(true);
columns.Bound(c => c.company_id).Width(0).Hidden(true);
columns.Bound(c => c.brand_id).Width(0).Hidden(true);
columns.Bound(u => u.brand_name).Title("Brand").Width("18%").HtmlAttributes(new { #class = "brkWord", #readonly = "readonly" });
columns.ForeignKey(u => u.connector_name, Model.CompanyConnectorList, "company_connector_id", "connector_name").Title("Connector").Width
("16%").HtmlAttributes(new { #class = "brkWord" }).EditorTemplateName("company_connector_id");
columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { #title = "Edit" })).Width("16%").Title("Edit");
})
.Editable(editable => editable.Mode(GridEditMode.InLine).CreateAt(GridInsertRowPosition.Top))
.Pageable(pageable => pageable.Refresh(true).PageSizes(GlobalCode.recordPerPageList).ButtonCount(GlobalCode.PageSize).Input(true).Numeric(true))
.HtmlAttributes(new { #class = "dynamicWidth" })
.Sortable(sorting => sorting.Enabled(true))
.Render();
}
Explanation: I've used ForeignKey. Bound it to the string column "connector_name". Connector_name is a comma separated list of IDs that I send from controller. Editor template is used here.
Issue: It works fine at the time of View/Display in Index but Edit does not show selected value. Also we do not get updated value in code behind on update click.
Is this correct way of implementing multiselect list or do I need to bind a collection property as a column in grid?
If I bind a collection property as a column then how would I be able to show comma separated string at the time of display?
Try below code:
function onEdit(e) {
var multiselect = $("#YourMutliselectDropdown").data("kendoMultiSelect");
var IDArray = [];
$(e.model.propertyName).each(function (index) {
var ID = e.model.propertyName[index].id;
IDArray.push(ID);
});
multiselect.value(IDArray);
}
I assume that propertyName is List of your collection and it contains id as property.
try it:
c.Bound(p => p.CompanyConnectorList).ClientTemplate("#= connectorsToString(data)#").EditorTemplateName("company_connector_id");
and js:
function connectorsToString(data) {
var list = data.company_connector_id;
var result = "";
for (var i = 0; i < list.length; i++) {
result += list[i].Name + ';';
}
return result;
}

Create serial number column in telerik mvc grid

I could create a grid with telerik mvc
<% Html.Telerik().Grid(Model)
.Name("ProductGrid")
.Columns(columns => {
columns.Bound(h => h.ProductName).Width("34%");
columns.Bound(h => h.Description).Width("60%");
columns.Bound(h => h.ProductID).Format(Html.ImageLink("Edit", "Products", new { Id = "{0}" }, "/Content/images/icon_edit.gif", "", new { Id = "edit{0}" }, null).ToString()).Encoded(false).Title("").Sortable(false).Width("3%");
columns.Bound(h => h.ProductID).Format(Html.ImageLink("Delete", "Products", new { Id = "{0}" }, "/Content/images/icon_delete.gif", "", new { onclick = string.Format("return confirm('Are you sure to delete this add on?');") },null).ToString()).Encoded(false).Title("").Sortable(false).Width("3%");
})
.EnableCustomBinding(true)
.DataBinding(databinding => databinding.Ajax().Select("_Index", "ProductGrid"))
.Pageable(settings => settings.Total((int)ViewData["TotalPages"])
.PageSize(10))
.Sortable()
.Render(); %>
but I need to add a serial number column in telerik grid.How can i do this?
I think the best way is to use template column like this.
<%
var sn = 0;
Html.Telerik().Grid(Model).Name("Grid").HtmlAttributes(new { style = "width:auto" })
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Template(c=> {%> <%: ++sn %> <% }).Title("S/N");
columns.Bound(c => c.CustomerNumber);
columns.Bound(c => c.Narration);
})
.Render(); %>
This way you don't have to be adding serial number property to your view models.
Hope this help?
I think the best way to do this is to add a SerialNumber column to your Product class which is your model and than just add another bound column to the grid like this:
columns.Bound(h => h.SerialNumber)
If you pass a List of Products you can populate the SerialNumber column like this:
List<Product> products = GetList(); // Your method to get data here
int counter = 1;
products.ForEach(x => x.SerialNumber = counter++);
If you want to support consistent numbers with paging you have to calculate yourself the initial value of the counter valuable. For this purpose you must have the current page and page size.
In MVC Web Grid
use this calculation
grid.Column(header: "#",
format: item => item.WebGrid.Rows.IndexOf(item) + 1 + Math.Round(Convert.ToDouble(grid.TotalRowCount / grid.PageCount) / grid.RowsPerPage) * grid.RowsPerPage * grid.PageIndex),

Resources