Save state of Widgets in ASP.NET MVC using jQuery and Json - c#

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.

Related

MVC drop down list onchange pass the selected value to the function in the controller and execute it

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

unable to assign hiddenfield value to select2 on postback

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);
}
});
});

Binding a dropdown on the onblur event of a textbox using jquery Ajax

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

Better way to speed up Binding dropdown list on another dropdown-list onchange in MVC 4 razor

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 ?

Return a list of values using Json

In my controller action, I call a method that returns me a a list of missing files. From here, I return this list to the .js file using Json:
foreach (string s in result.Value.MissingImages)
{
missingImages.Add(s.ToString());
}
return Json(new { returnVal= missingImages });
On the .js file, I would like to display a list of these files to the users. How should I process and display this list on the front end?
$("#Images").click(function () {
$.post('/File/ImageUtil', function (data) {
//display the missing file list to the user here??
});
});
You could define a result placeholder:
<div id="result"></div>
and then loop through the returned collection of strings and inject them into the result:
$("#Images").click(function () {
$.post('/File/ImageUtil', function (data) {
var result = $('#result');
result.empty();
$.each(data.returnVal, function() {
result.append(
$('<div/>', {
text: this
})
);
});
});
});
alert(JSON.stringify(data));
More complicated rendering requires better knowledge of your browser side rendering.

Categories

Resources