I am trying to assign value to select2 control from a hiddenfield in clientside script. Value is not assigned to select2 control after postback for the following code.
$(document).ready(function () {
$("#cboIndustry").select2();
$.getJSON(uriSector+ '/' + 'GetIndustrySectors')
.done(function (data) {
$.each(data, function (key, item) {
$("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
});
});
$("#cboIndustry").on('change', function () {
if ($("#cboIndustry").val() != "-1") {
var id = $("#cboIndustry").val();
$('#HiddenIndustrySectorID').val(id);
SelectedName = $('#cboIndustry option:selected').text();
$('#HiddenIndustrySectorName').val(SelectedName);
}
});
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
$("#cboIndustry").select2().select('val',SelectedIndustry);
});
However value get assigned if I put alert before assigning
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
alert(SelectedIndustry);
$("#cboIndustry").select2().select('val',SelectedIndustry);
// These steps I have included, for retaining value in select2 on postback.
What could be the reason? Please help me.
Why don't use this line
$("#cboIndustry").select2().val(SelectedIndustry);
BTW i have not tested
$('#HiddenIndustrySectorID').val(id);
Change this line to
document.getElementById("HiddenIndustrySectorID").value =id;
and try
$(document).ready(function () {
$("#cboIndustry").select2();
$.getJSON(uriSector+ '/' + 'GetIndustrySectors')
.done(function (data) {
$.each(data, function (key, item) {
$("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
});
//This change solves my problem
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
$("#cboIndustry").select2().select('val',SelectedIndustry);
});
$("#cboIndustry").on('change', function () {
if ($("#cboIndustry").val() != "-1") {
var id = $("#cboIndustry").val();
$('#HiddenIndustrySectorID').val(id);
SelectedName = $('#cboIndustry option:selected').text();
$('#HiddenIndustrySectorName').val(SelectedName);
}
});
});
Related
i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor
I am having a HttpPost request sending back an object Value.
I would like to make the ComputerLocation div appear when the object Value is true(s.IsComputer is a bool).
Currently nothing happens.
I tried to debug it using Firebug and verified that actually the request posts back the object Value:true, but when i check my result.Value, Value is shown as undefined.
Please check what I am doing wrong?
Script:
<script type='text/javascript'>
$(document).ready(function () {
$('#typeddl').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#typeddl').val() },
success: function (result) {
$('#ComputerLocation').toggle(result.Value === true);
}
});
});
$('#typeddl').trigger('change');
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(int itemTypeId)
{
//pseudo code
var data = from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer };
return Json(data);
}
Use First method to get single result, because your query returns an IQueryable<T>
var data = (from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer }).First();
Then return your result like this:
return Json( new { Value = data.Value });
I have a textbox whose value when passed to sp should return a list. I have to bind this list to Dropdown using jQuery Ajax. I have written the sp but my problem is how to bind the dropdown depending on value of textbox in the onblur event of Textbox.
Kindly help. And please excuse for typing errors if any.
i have done similar in my project.
$( "#target" ).blur(function() {
alert( "Handler for .blur() called." );
$.ajax({
url: '../GetRolesAndPriviledgeServlet?filepath='+path+'&type='+type,
type: 'post',
success:function(response){
obj = JSON.parse(response);
$('#DropDownListAssigned').empty();
for (var i=0; i <obj.length ; i++)
{
var oSelField = document.getElementById("DropDownListAssigned");
var oOption = document.createElement("OPTION");
oOption.text = obj[i+1];
oOption.value = obj[i+1];
oSelField.options.add(oOption);
}
},
error:function(){
}
});
});
Try this one
$(document).ready(function () {
$('#txtboxid').focusout(function () {
var yourvalue = $('#textboxid').val();
$.post("/your/url", { Parametername : yourvalue }, function (result) {
$.each(result, function (key, value) {
$('#dropdownid').append($("<option></option>").html(value).val(value));
// Dropdown Binding
});
}, "json");
});
});
Note : Parameter must be same as your controller for example public void data(string nval) means your parameter name also nval
Change function of a dropdown list listDeptID is as below
<script type="text/javascript">
$(function () {
$('#listDeptID').change(function () {
var selectedDepartmentId = $(this).val();
$.getJSON('#Url.Action("GetCities")', { departmentId: selectedDepartmentId }, function (items) {
var citiesSelect = $('#listcityID');
citiesSelect.empty();
$.each(items, function (index, city) {
citiesSelect.append(
$('<option/>')
.attr('value', city.cityId)
.text(city.cityName)
);
});
});
});
});
this already working fine.. But its takes some time to bind.
items is Ienumerable object converted as JSON object. I think the looping takes time.
Is there any other method to do the same ?
I am using ASP.NET MVC in C#
I have a page where the user can move different Widgets around the page, and I now need a method to save the state of the widgets. I am using jQuery in the HTML page, and the jQuery posts the new page layout using JSON. I am unsure how to read the JSON in the controller.
The code I'm using is based on this example here - http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/, but the code for saving the result is in PHP.
jQUERY
<script type="text/javascript" >
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
//Save state on change of collapse state of panel
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
start: function (event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find('.dragbox-content').toggle();
},
stop: function (event, ui) {
ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
//Pass sortorder variable to server using ajax to save state
$.post('/Widgets/SaveLayout', 'data=' + $.toJSON(sortorder), function (response) {
if (response == "success")
$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#console').fadeOut(1000);
}, 2000);
});
alert(sortorder);
}
I am willing to consider alternative ways to do this, as I may not have chosen the best way to do this.
Phil Haack's blog post http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx specifically handles the problem you are trying to solve and it works great.
Hope this helps.
Why not use a cookie? This would save you from having to pull that data back and forth from the server so much.