MultiSelectList change dynamically ASP.NET MVC Razor - c#

I'm using this code to generate a multi-select2. Tags is a MultiSelectList.
#Html.DropDownList("mail-to", (IEnumerable<SelectListItem>)ViewBag.Tags, String.Empty, htmlAttributes: new { multiple = "", #class = "form-control select2 select2-multiple" })
$("#mail-to").select2({
minimumResultsForSearch: -1,
closeOnSelect: false,
});
It works great. Now I want to change the select options with another ViewBag based on a checkbox field checked change event.
Is there a way to change select2 data populated with this type of list or a MVC way to do it?
What I've tryed:
$("#mail-to").select2({
tags: #ViewBag.TagsArea, //or tags: #Html.Raw((IEnumerable<SelectListItem>)ViewBag.TagsArea)
});

Managed to solve it:
var areas = #Html.Raw(Json.Encode(ViewBag.Tags)) ;
$("#mail-to").empty();
$.each(areas, function (index, element) {
$("#mail-to").append($('<option/>', {
value: element.Value, text: element.Text
}));
});

Related

How to take value from DataValueField() of a Kendo().DropDownList() on change event

I'm using kendo grid and editor template for showing my data. in editor I've given id to DataValueField() and name to DataTextField() of kendo dropdown list. In change event, I'm not able to get the DataValueField(). see the following code
This is my editor template MemoCarrier.chtml
#using System.Collections
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
.Events(e =>
{
e.Change("MemoCarrier");
})
)
Here is my on change function
function MemoCarrier(e) {
var AirlineName = this.value();
alert(AirlineName) //it displays PARTNERNAME instead of PARTNERID
}
Currently I'm getting name ie;DataTextField() value. instead of that, I need DataValueField().
Thanks for suggestions in advance!
so based on your comment the easiest way to do this would probably use the data-bind attribute to simplify the process of binding the model. Assuming you are using the MVC helper for the grid as well.
so taking your code and adding this:
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum", data_bind="value:{yourProperyNameHere}" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
)
So hopefully you can see all I am doing is adding a new HtmlAttribute property to the control for you. All you need to do is put whatever property is meant to be the value for this.
Depending on if this value is a complex (object) or simple (string, int etc) primitive type you may need to set the Primitive property to true so that only the valuefield e.g the id you are assigning is bound back to the grid's row model.

DataValueField Missing in kendo Autocomplete

I am using kendo autocomplete control in my MVC project(Server side filtering).It list the data correctly. But the problem is when i submit the data to server the autocomplete value id is missing. Because there is no DataValueField attribute in this control. The bellow code is i am using
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("function", "controller")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
How can i send the value to the server.
Thank you..
Since AutoComplete helper doesn't have DataValueField attribute, you need to use other HTML helper as workaround to pass another property value. Suppose your viewmodel has this setup:
public class ViewModel
{
// ID property example
public int PatientID { get; set; }
// other properties
}
You can create a hidden field or read-only textbox to store ID property mentioned above inside Razor view:
#Html.HiddenFor(m => m.PatientID)
Then, assign its value attribute from client-side script by creating a function which reads item index from autocomplete helper:
function selectPatient(e) {
var item = this.dataItem(e.item.index());
$('#PatientID').val(item.PatientID);
}
And finally set the function name bound for Events attribute:
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
// add this line
.Events(ev => ev.Select("selectPatient"))
.DataSource(source => {
source.Read(read => {
read.Action("function", "controller")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
By following this setup, the PatientID property should have ID of the selected value from autocomplete helper when user submitted the form.
This is a known limitation of the AutoComplete widget. One way around it is to add an attribute via a template to store the data value on the control:
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("function", "controller").Data("onAdditionalData");
})
.ServerFiltering(true);
})
.Events(events => events.Select("onPatientSelected"))
.Template("<span data-recordid=\"#= data.ID #\"> #: data.ID # – #: data.Name #</span>")
)
This assumes ID and Name are properties of the patient object.
Then you can handle the Select event to get the stored ID value when a selection is made:
function onPatientSelected(arg) {
var selectedPatientID = arg.item.find('span').data('recordid')
// do whatever with the ID, such as sending it to the server
}
You can access the dataItem in javascript, and then access the value property.
If you call myKendoAutoCompleteControl.dataItem() it will give you the currently selected item as an array of key/value pairs.
$("#myKendoAutoCompleteId").kendoAutoComplete({
dataTextField: "Text",
dataValueField: "Value",
dataSource: mydatasource,
filter: "startswith",
placeholder: "Search..."
//separator: ", "
});
var myKendoAutoCompleteControl =
$("#myKendoAutoCompleteId").data("kendoAutoComplete");
// once user has selected an item in the kendo auto complete control, you
can access the selected item.
var dataItemArray = myKendoAutoCompleteControl.dataItem();
var value = dataItemArray.Value

Is there a simple way to display both the value and text fields in a drop-down list in MVC (razor)?

I have a simple view dropdownlist in razor,
#Html.DropDownList("Client_Id", null, htmlAttributes: new { #class = "form-control" })
and for the controller I have the following viewbag,
ViewBag.Client_Id = new SelectList(db.ClientMetadatas, "Client_Id", "Name");
Now is it possible to have a simple way, to display the client_id along with the Name in the dropdown ?
I would suggest creating an anonymous class using the Select extension method.
ViewBag.Client_Id = new SelectList(db.ClientMetadatas.Select(x => new { ClientId = x.Client_Id, CombinedProperty = x.Client_Id.ToString() + " " + x.Name }).ToList(), "ClientId", "CombinedProperty");
Please let me know if this was able to assist you!

Having two values on SelectList() in asp.net

I'm trying to develop a website using asp.net mvc 4 & EF6 where I'm using dropdownlist to assign datas to my required textboxes. So far I've managed to assign data to two textboxes where one holds the value of the selected item of dropdownlist & one holds the text given for the selected item. But I need to add another value from the selected item. My codes are below,
Controller
ViewBag.Clients = new SelectList(db.ClientInfoes, "age", "fullname"); //This is given
ViewBag.Clients = new SelectList(db.ClientInfoes, "id", "age", "fullname"); //I want something like this
View
#Html.DropDownList("Clients", "Select...")
// Textboxes are populated automatically by using jQuery
#Html.TextBoxFor(a => a.Fullname, new { id = "clientName", #readonly = "readonly" })
#Html.TextBoxFor(a => a.Age, new { id = "clientAge", #readonly = "readonly" })
How can I assign more than one value in the SelectList? Any way I can do that would be fine. Need this help badly. Thanks.
It looks like you want to show name and age both in the dropdown text, in that case you need to project the result coming from database :
var ClientInfoes = db.ClientInfoes
.Select(x=>
new {
id = x.id,
name = x.fullname+","+x.age
});
ViewBag.Clients = new SelectList(ClientInfoes, "id", "name");

How to edit data inside the WebGrid Helper

I have a WebGrid full of lots of products, and I want to be able to edit the quantity for each row in the web grid and update the Cart table in the database when the textChanged event is raised on the corresponding textbox.
But is this even possible with WebGrid? I have not found anything that would suggest it's possible. I would really appreciate any help at all.
It's possible to attach a change event to the textboxes.
I set my grid up like the following:
#grid.GetHtml(
htmlAttributes: new { cellspacing = "2px", cellpadding = "2px" },
columns: grid.Columns(
grid.Column("Id"),
grid.Column("Description"),
grid.Column("PacketQuantity"),
grid.Column("ThickCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThickCover, new { #class = "thickCoverInput", #data_value = p.Id });
}),
grid.Column("ThinCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThinCover);
})
)
)
Then I had the following script to wire up the changes:
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$('.thickCoverInput').change(function(event) {
alert(event.currentTarget.attributes["data-value"].value);
alert(event.currentTarget.value);
// Here you can post data to an action to update your table
});
});
</script>
When I changed the value in the textbox, I was able to get two alerts. One for the Id of the Product and the other is the new value.
Hope this is what you were looking for.

Categories

Resources