Bespoke Software Solutions in C#.Net, ASP.Net MVC, JQuery, MEF and more
Posts tagged ajax
Update Form Fields with JSON result in ASP.NET MVC
Oct 5th
Wouldn’t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said “No” leave now!
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.
Lets use a simple “Person” model and have a look at the ASP.NET MVC action:
public ActionResult GetPerson(int id)
{
var person = Context.GetPerson(id);
return Json(new
{
success = true,
model = new
{
person.Id,
person.Name,
person.Surname,
person.Age,
}
});
}
As you can see this returns a DTO (data transfer object) as JSON result and is ready to be consumed via AJAX…
$.getJSON("/Person/1", function(data) {
if (data.success) {
$.updateForm(data.model);
} else {
alert("An error occurred");
}
});
All we then need is the magical “$.updateForm” method that contains all the voodoo:
jQuery.updateForm = function(model) {
// we iterate through all the properties
for (var property in model) {
// evaluate the expression to get the value
var propertyValue = eval("model." + property);
// and update the field
$("#" + property).val(propertyValue);
}
};
Currenty this will work fine for textboxes and textareas as this was all the functionality I needed for now. If anyone extends this for “select”, “checkbox”, “radiobutton” etc… please share with us so I can update this post.
JQuery function to populate a select box
Sep 4th
Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the ‘populateSelect’ method in a global .js file and use it throughout your project as ‘$.populateSelect(args…)’
ASP.NET MVC Action Method
public ActionResult GetUsers()
{
var data = Service.QueryUsers()
.Select(x => new {value = x.Id, text = x.Name});
return Json(data);
}
Usage:
var url = "<%=Url.Action("GetUsers", "UserController") %>";
$.getJSON(url, function(data, textstatus) {
$.populateSelect("#someSelectBox", data);
});
Global Method:
// JQuery Method
jQuery.populateSelect = function(selectId, data) {
$.each(data, function() {
var option = new Option(this.text, this.value);
var dropdownList = $(selectId)[0];
if ($.browser.msie) {
dropdownList.add(option);
} else {
dropdownList.add(option, null);
}
});
};
Removing all Items from a select list is just as simple:
$("#mySelectList")
.find("option")
.remove();
And lastly how to Append or Prepend items to the list:
// Add options to the end of a select
$("#mySelectList")
.append("");
// Add options to the start of a select
$("#mySelectList")
.prepend("");
Turn your hyperlinks into ajax calls
Sep 4th
When designing a rich user interface with JQuery it is very useful to replace default hyperlink functionality with ajax calls. The first method will turn the <a> functionality into an ajax call using the “href” attribute as source. The second method will do the same, but will ask “Are you sure?” first (very usefull for deletes etc…).
The ajaxReload var can then be set to a function that would handle the ajaxCall. These methods would usually be located in a ‘common.js’ file.
// GLOBAL VARS
var ajaxReload = function() { };
$(".ajaxCall").live("click", function(e) {
e.preventDefault();
$.get($(this).attr("href"), ajaxReload);
});
$(".yesNoAjaxCall").live("click", function(e) {
e.preventDefault();
if (confirm('Are you sure?')) {
$.get($(this).attr("href"), ajaxReload);
}
});
The reason behind using ‘live’ instead of ‘bind’ or ‘click’ is because I want to bind all future loaded ‘a’ tags too. Usually ‘bind’ or ‘click’ will only find the static ‘a’ tags that are available on page load.