Dropdownlist in MVC 4 - asp.net-mvc

I am trying to use simple dropdownlist in my edit form, where user can correct information, with help of dropdownlist.
So I use this:
public ActionResult Edit(string zonesList)
{
using (var dbVn = new userDbEntities())
{
...
var zList = new List<string>();
var zQuery = from d in dbVn.TimeZoneTables // take data for List from table
select d.TimeZone;
zoneList.AddRange(zQuery.Distinct());
ViewBag.zonesList = new SelectList(zList);
}
}
And in View I put this code:
Zones: #Html.DropDownList("zonesList")
My question is, how in View use this:
#Html.DropDownList("zonesList")
on this code
#Html.EditorFor(model => model.TimeZoneId)
Thanks for any idea.

Use jquery or javascript as below:
#Html.DropDownList("zonelist", new SelectList(ViewBag.zonesList,<value>,<text>),"Select Vendor/customer",new{ #class = "form-control",required = "required",#id="zone" })
Now want to change editor for value
#Html.EditorFor(model=>model.TimezoneId,new{#id="time"})
Jquery code for above
<script type="text/JavaScript">
$(document).ready(function () {
$("#zone").change(function(){
var t =$("#zone").val();
if(t==/*somevalue*/)
{
//set value for time id
//like $("#time").val(/*new val*/)
}
});
});
</script>

As I am using Time Zones I find cool solution that works only for time zones. First I actualy don't need table with time zones saved, but simple in my View I call library of .Net timezones:
#Html.DropDownListFor(o =>o.TimeZoneId, TimeZoneInfo.GetSystemTimeZones().Select(o => new SelectListItem{Text = o.DisplayName, Value = o.Id}))

Related

Select2 Asp.net MVC - Dropdownlist is not valued with initial data

I am using a select2 using MVC 5 and C#.
I'm having trouble with the dropdownlist (select2) loading with initial data of the model.
The items passed in the corresponding binding field properly valued, but they are not shown in select2!
I mean, despite the list of the ViewModel field correctly valued by the controller, the dropdownlist (select2) is not valued correctly, as if the binding model did not work.
Needless to say, I'm googling for 1,5 days.
Fortunately (:)) I have no problem at the loading of select2 with all items, the dropdownlist works correctly even on the post, even I can take the selected items.
Many Thanks to all
P.s: Now that I'm writing, I have a doubt; Could be that select2 doesn't work with List ?
View
#section scripts{
...
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
}
#Html.DropDownListFor(model => model.MezziStraSelect, Model.MezziStraOrdinari, new { style = "width: 100%", #class = "form-control" })
JS
$(document).ready(function () {
//...
$("#MezziStraSelect").select2({
placeholder: "Select one or more items",
multiple: true,
allowClear: true
});
#if ( Model.MezziStraSelect == null)
{
<text>$("#MezziStraSelect").val(null).trigger("change");</text>
}
}
ViewModel
public Guid[] MezziStraSelect { get; set; }
public MultiSelectList MezziStraOrdinari { get; set; }
Controller
//Load List MezziStraOrdinari
var _stra = m.GetMezziStraordinari().Select(x => new
{
id = x.VoceSpesaID,
desc = x.VoceSpesa
}).ToList();
//view model set field
vm.MezziStraOrdinari = new MultiSelectList(_stra, "id", "desc");
//Load array Mezzi used from item selected
List<Guid> _mezziStraUsati = new List<Guid>();
var elems = dc.ItemSelected.FirstOrDefault(x => x.ItemID.ToString() == _guidSelected);
if (elems!=null)
{
elems.VociSpese.ToList().ForEach(x =>
{
if (x.VociSpesa.Straordinario == true)
_mezziStraUsati.Add(x.VoceSpesaViaggioID); //VoceSpesaViaggioID is GUID
});
if (_mezziStraUsati.Count>0)
vm.MezziStraSelect = _mezziStraUsati.ToArray(); //Guid[]
}
The initial loading of the Select2 unfortunately the binding cannot set the initial values!
So reading the Select2 documentation to this link , I had to proceed with a manual upload via JS.
Practically to try to do an human thing (I hope it is), I created an Extension method in the backend of the Model field
Extension Method
public static string ToSelect2Array<T>(this T[] values)
{
var resp = string.Empty;
values.ToList().ForEach(x => resp += $"'{x.ToString()}',");
if (resp.Length > 0)
resp = resp.Substring(0, resp.Length - 1);
return resp;
}
and then in JS client side, I call it like this:
VIEW (script JS)
#if ( Model.MezziStraSelect != null)
{
<text>
$("#MezziStraSelect").val([#Html.Raw(Model.MezziStraSelect.ToSelect2Array())]);
$("#MezziStraSelect").trigger('change');
</text>
}
else
{
<text>$("#MezziStraSelect").val(null).trigger("change");</text>
}
This is working quite well, but is it possible that there is no way to get it to bind automatically?
I would be curious to know other solutions, more elegant than this I would be grateful for!

Kendo Drop Down List not showing data

I am trying to create a Kendo Dropdownlist and it will not call the read.Action for some reason. I cannot figure out what I am missing.
I have set the read.Action to different methods and it works but it just will not call it to this specific method. I have verified that I am spelling it correctly and I've set breakpoints on everything to find what it runs.
#(Html.Kendo().DropDownList()
.Name("productionline-dropdown")
.DataTextField("Id")
.DataValueField("Name")
.DataSource(source =>
{
source.Read(read => { read.Action("GetDropDownList", "Home"); });
})
)
[HttpPost]
public JsonResult GetDropDownList()
{
var productionLines = _productionLineService.GetAll().Select(x => new ProductionLineViewModel
{
Id = x.Id,
Name = x.Name,
CreatedAt = x.CreatedAt,
UPE = x.UPE,
ComputerName = x.ComputerName,
ActiveLine = x.ActiveLine
});
return Json(productionLines, JsonRequestBehavior.AllowGet);
}
I want my DropDownList to populate with the Names of the ProductionLines not the Ids. Thanks
This is because the action is decorated with HttpPost, while the control apparently sends Get (quite logically) to fetch the data. Remove this attribute, and that should fix it.

Kendo control value in the event is the controls previous value

I am trying to understand why this isn't working. If i set the value of myTextBox to 5 then trigger the change event. the value for my myTextBox is null. If i change the value to 10 then fire the event again, the value will be the previous one (5). I've compared it to one of the many textboxes working on the form and they appear the same. The only difference is the value property in the wrapper object is set in the ones that work but behind in the one that doesn't. Digging into the both objects element property, i see the values are correct and current. Any help would be appreciated.
Model Property
[UIHint("Decimal")]
[Display(Name = "Example")]
public decimal? MyTxt{ get; set; }
Template (Decimal.cshtml):
#model decimal?
#{
var defaultHtmlAttributesObject = new { style = "width:100%" };
var htmlAttributesObject = ViewData["htmlAttributes"] ?? new { };
var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesObject, defaultHtmlAttributesObject);
}
#(Html.Kendo().NumericTextBoxFor(m => m)
.Format("#.00")
.HtmlAttributes(htmlAttributes)
)
UI Declaration
#Html.EditorFor(m => m.MyTxt, new { htmlAttributes = new { #style="width: 100%", #readonly = "readonly" } })
Javascript:
var myTextBox = $('#MyTxt').data('kendoNumericTextBox');
$(document).on('change', '#foo', function(){
var test = myTextBox.value();
})
Update:
In the document ready function i was binding the change event like this:
$('#MyTxt').change({ source: $('#MyTxt'), destination: someObject, isTwoMan: true, crewType: LaborType.Set }, SomeCalcFunction);
The jQuery change event fires nefore the kendo one thus the delay in getting the correct value. The fix was to read the manual and bind to the event the kendo way
the issue was in the way i was binding to the change event.
$('#MyTxt').change({ source: $('#MyTxt'), destination: someObject, isTwoMan: true, crewType: LaborType.Set }, SomeCalcFunction);
will fire before the kendo event does. Changing it the kendo way fixed my issue
$("#MyTxt").bind("change", function (e) {
var event = jQuery.Event('change', {
source: $("#MyTxt"),
destination: someObject,
isTwoMan: true,
crewType: LaborType.Set
});
SomeCalcFunction(event);
});

selectedValue from view to controller MVC

Filter records in index view using dropdown list . How replace xxxxxxx with selectedValue from dropdownlist to filter. I am not sure how to select the selectedValue from dropdown list in the view. The controller code and the view code is below. I know its a small problem. But I am trying to find for some hours.The filter is working fine if i replace with xxxxxx with 1 , 2 etc.But I want to change xxxxx with selectedValue from Dropdown list.
controller code
ViewBag.doctorsid = new SelectList(db.doctors, "doctorsid", "doctorsname",selectedValue);
return View(appointments.Where(d => d.doctorsid == xxxxxxx).ToList());
view code
#Html.DropDownList("Doctorsid","Select Doctor")
Use script given bellow
Script
$("#Doctorsid").change(function () {
var doctorsid = $('#Doctorsid').val();
var url = "/ControllerNmae/ActionResultName/+doctorsid ;
window.location.href = url;
});
Use a Model with variables for list and drop down value instead of passing list directly to view
Controller:
ViewBag.ClientTypeID = new SelectList(db.ClientType.Where(ct => ct.IsDeleted != true), "ID", "ClientTypeName");
View:
#Html.DropDownListFor(m => m.ClientTypeID, new SelectList(ViewBag.ClientTypeList, "Value", "Text"), new { #class="drop"})

How to create a dynamic dropdown in mvc

How to create a dropdown whose option values are coming from controller.
controller will be getting it from database table's any column value.
for example if that dropdown is for selecting country, and i have 3 country in my database table's country column, in dropdown it should show the 3 country. And if I add one more value in country table, that also should come in dropdown.
I am new to MVC an this is found bit difficult. I am using mvc5.
NB: since I already one model is refered inside the view, I cant add the model for this dropdown
I have done the same in my own website. This is how I do it:
Firstly, create a action for controller which returns JSON value:
public ActionResult GetCountryNames()
{
List<string> CountryNames = new List<string>();
CountryNames = context.GetCountries(); // your EF context to get countrynames from database
return Json(CountryNames.ToArray());
}
Then in your view add this html mark up:
<select id="countrylist" onchange="DoSomething();"></select>
This is your dropdownlist. It has javascript function declared in "onchange" event, if you want to do something when value changes.
Lastly, you need to add your javascript function, which does ajax call to your controller action, gets values and set it to your dropdownlist:
function GetCountryList() {
var serviceURL = '/Home/GetCountryNames';
$.ajax({
type: "post",
dataType: "json",
url: serviceURL,
success: successFunc,
async: false,
error: errorFunc
});
function successFunc(data, status) {
var countrylist = $('#countrylist');
countrylist.empty();
for (var i = 0; i < data.length; i++) {
var $option = $("<option>", { id: "option" + i });
$option.append(data[i]);
countrylist.append($option);
}
}
function errorFunc(data, status) {
alert('error');
}
}
And when your document is ready, run function GetCountryList().
Probably easiest is to do it with jQuery. Like this:
<script type="text/javascript">
$(document).ready(function () {
GetCountryList();
});
</script>

Resources