Kendo DropDownListFor in EditorTemplate - dynamic

I am creating a Dynamic Kendo Grid using GridBoundColumnBuilder().
I loop through all of the controls on the previous page to create the grid.
For example with myTextbox(), myCheckbox(), etc.
These create columns in the grid. I have all of the columns creating and populating with data.
My issue is with the Dropdownlist and the Multiselect list, they populate with data but do not display the correct data when the grid is created.
The dropdown list displays the value, not the text of the previous control:
1 = My
2 = Data
The Dropdownlist will display 1 instead of My. And, the Multiselect only displays [object Object].
When you click on either of the controls in the grid it switches to show the proper text, but loses it when you click off.
Any ideas of what I am doing wrong?
foreach (ControlBase control in flatColumns)
{
GridBoundColumnBuilder<dynamic> thisColumn;
if (control.Lookups != null && control.Lookups.Any())
{
if (!control.IsMultiSelect){
thisColumn = column.Bound(control.ControlType, control.ColumnName).Title(control.Description);
thisColumn.EditorTemplateName("DropDownList");
thisColumn.Width(250);
}
else
{
thisColumn = column.Bound(control.ControlType, control.ColumnName).Title(control.Description);
thisColumn.EditorTemplateName("MultiDropDownList");
thisColumn.Width(250);
}
}
}
Dropdown Template
#(Html.Kendo().DropDownListFor(m => m).HtmlAttributes(new { #class = "form-control" })
.BindTo((IEnumerable) ViewData[currentColumn + "List"])
.DataTextField("Text")
.DataValueField("Value")
.ValuePrimitive(true)
.Text("Value")
Multiselect Templage
#(Html.Kendo().MultiSelectFor(m => m)
.HtmlAttributes(new { #class = "form-control" })
.BindTo((IEnumerable)ViewData[currentColumn + "List"])
.DataTextField("Text")
.DataValueField("Value")

Have you tried changing the .Text to display the Text rather than the Value?
.DataTextField("Text")
.DataValueField("Value")
.ValuePrimitive(true)
.Text("Text")

Related

ASP.NET MVC5 setting dropdown list value within a loop on the View

I have a collection that I populate in the controller MenuitemDetails and this populates a property on the view model.
The collection has 3 properties and multiple records
Id, Title and State
State is an integer value which relates to a dropdown list selected value.
The viewmodel also contains a selectList property (stateList) which is used to populate the dropdownlist items on the view.
I'm trying to repopulate the form for an edit action - with the same dropdown item selections
<table>
#for (int counter = 0; counter < Model.MenuitemDetails.Count; counter++)
{
<tr>
<td>
#Model.MenuitemDetails[counter].Title
#Html.DropDownListFor(i => Model.MenuitemDetails[counter].state, Model.stateList)
</td>
<hr />
</tr>
}
</table>
I can't seem to get the values of the dropdown to display the appropriate values selected.
Rather than pass in a select list in the viewmodel it can be created in the razor view and in this way you can use the overload for creating the select list to determine the value to bind.
In the example I am using telerik mvc dropdown list but the same applies in terms of creating the selectList in the razor and with a property to bind to which will determine its state.
#(Html.Kendo().DropDownListFor(m => m.Entity.ProductId)
.DataTextField("Text")
.DataValueField("Value")
.Filter("contains")
.HtmlAttributes(new { #class = "form-control" })
.BindTo(new SelectList(Model.Products, "Id", "FullName", Model.Entity.ProductId)))
You can also try to use an editortemplate for this sort of things like so:
#(Html.Kendo().DropDownListFor(m => m)
.OptionLabel("--Select Value--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("MethodName", "ControllerName").Data("dataforMethod");
});
})
.Enable(true)
.AutoBind(true)
)
In the .Data() part on the read you dont need to use it only if you have some parameters you need int the funtion to get the dataset

how to populate a dropdownlist based on another dropdownlist selected value in mvc 4?

I have created two Drop Down List. On selecting a value from first dropdown list second dropdown list should be filled this is my code in View
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.DropDownList("Id", ViewData["Id"] as List<SelectListItem>, new { })
<button type="submit">next</button>
}
#Html.DropDownList("Id", ViewData["Id1"] as List<SelectListItem>)
When I click on next button second dropdown is getting populated. Same thing I want to do when I select a particular item from first list. I don't want to use jquery is there any way to do?
Or is there any way how I can generate postback when I select value from first list?
I think you can put the first dropdown inside a form and include the change attribute to this dropdown:
#{ Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("Id", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
Then, in the controller, you should include some code to populate the second dropdown.

Multiple radio button groups in MVC 4 Razor

I need to have multiple radio button groups in my form like this:
I know it's simply done by specifying the same "name" html attribute for each group.
HOWEVER
MVC doesn't let you specify your own name attribute when using html helper like this:
#Html.RadioButtonFor(i => item.id, item.SelectedID, new { Name = item.OptServiceCatId })
Because it looks at each tag's "name" attribute (not "id") to map/bind the form to the model which the controller receives, etc.
Some said that specifying each with the same "GroupName" attribute will solve the problem, but it didn't work either.
So, is there any way which works ?
EDIT:
Here's my view (simplified):
#model Service_Provider.ViewModels.SelectOptServicesForSubServiceViewModel
#foreach (var cat in Model.OptServices)
{
//A piece of code & html here
#foreach (var item in cat.OptItems.Where(i => i.MultiSelect == false))
{
#Html.RadioButtonFor(i => item.id, item.SelectedID, new { GroupName = item.OptServiceCatId })
<br />
}
}
NOTE:
My model is a List<OptServices>:
public List<OptServices> Cats {get; set;}
And OptServices has a List of OptItems inside:
public class OptServices
{
//a few things
public List<OptItems> Items {get; set;}
}
all you need is to tie the group to a different item in your model
#Html.RadioButtonFor(x => x.Field1, "Milk")
#Html.RadioButtonFor(x => x.Field1, "Butter")
#Html.RadioButtonFor(x => x.Field2, "Water")
#Html.RadioButtonFor(x => x.Field2, "Beer")
Ok here's how I fixed this
My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.
Here's the final 'working' pseudo-code:
#foreach (var cat in Model.Categories)
{
//A piece of code & html here
#foreach (var item in cat.SubCategories)
{
#Html.RadioButton(item.CategoryID.ToString(), item.ID)
}
}
The result is:
<input name="127" type="radio" value="110">
Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.
Thanks to all of the people who helped me solve this ;)
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
List<SelectListItem> items = new List<SelectListItem>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");
foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}
ViewBag.TiposPost = new SelectList(items, "Value", "Text");
In the View, I used a foreach to build a radiobutton.
<div class="form-group">
<div class="col-sm-10">
#foreach (var item in (SelectList)ViewBag.TiposPost)
{
#Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
<label class="control-label">#item.Text</label>
}
</div>
</div>
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
#Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
#Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
You can use Dictonary to map
Assume Milk,Butter,Chesse are group A (ListA)
Water,Beer,Wine are group B
Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);
At View , you can foreach Keys in dataMap and process your action

How to display values in a Kendo UI Grid custom popup template

I have a MVC View with a simple Kendo UI Grid:
#(Html.Kendo().Grid(Model.Positions)
.Name("Test")
.Columns(columns =>
{
columns.Bound(p => p.Name);
columns.Command(command => { command.Edit(); });
})
.Editable(ed=>ed.Mode(GridEditMode.PopUp).TemplateName("Position").Window(w => w.Width(600)).Window(w => w.Title("Byrå")))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model => model.Id(p => p.Id))
.Update(update => update.Action("Update", "Office"))
.Read(read => read.Action("Get", "Office")
)
)
)
Under Shared/EditorTemplate I have added Postion.cshtml under Shared/EditorTemplates. The edit open as it shoulds and everything is fine if I use for example:
#Html.TextBoxFor(model => model.Name)
However, I can't use LabelFor since that will display the name of the property and not the value. It also seems like the grid instantiate the popup together with the grid. The values in TextBoxFor is updated when I click on Edit, but if I use #Model.Name it does not. It will always be empty.
I also tried and hide some fields depending on the value of one of the fields, but since I can't use #Model it wont work.
Anyone know how to get around this?
One of Kendo's answers to me was something like this. I haven't got it to work in my case yet, but it might help you. If you came up with a different solution to this issue could you share it?
In you custom editor.
text/javascript
function sendName() {
var grid = $('.k-grid').data().kendoGrid;
var tr = grid.tbody.find('.k-grid-edit-row');
var model = grid.dataItem(tr);
var result = {
name: model.Name
};
return result;
}
They are inspecting the html and assigning first the grid, then the selected row of the grid then mapping the fields of the row to the columns of the Grid.

Html.LabelFor is always displaying property name instead of value

In my MVC4 project, I am showing Checkbox and its corresponding Label so that when the label is clicked the corresponding checkbox will be checked. But when i use the #Html.LabelFor it is displaying property name instead of showing its value. Also when i click the label the corresponding checkbox is not getting checked. What's wrong here ?
#for (int i = 0; i < Model.AddOns.Count; i++)
{
#Html.CheckBoxFor(m => m.AddOns[i].IsActive)
#Html.LabelFor(m => m.AddOns[i].Name)
#Html.HiddenFor(m => m.AddOns[i].Id)
}
When i use DisplayFor it is showing value but not checkbox getting checked on clicking the label.
You want the label to relate to the checkbox for IsActive, but the label to read the Name. So the LabelFor should refer to the IsActive property, and the label string just gets passed in as a second param.
I think you want this:
#for (int i = 0; i < Model.AddOns.Count; i++)
{
#Html.CheckBoxFor(m => m.AddOns[i].IsActive)
#Html.LabelFor(m => m.AddOns[i].IsActive, Model.AddOns[i].Name)
#Html.HiddenFor(m => m.AddOns[i].Id)
}