ASP.NET MVC Load page with AJAX - asp.net

I have this situation:
A page with an accordion with 2 tabs, one has a list of paymentmethods, the second has a summary of the order with orderlines, amounts and totals (rendered as partialview). Selecting a paymentmethod causes the order totals to be recalculated, extra costs etc might apply.
What is the recommended way to display the new ordersummary after a paymentmethod is selected, using AJAX?
Doing an AJAX call and getting all the new amounts, orderlines, etc and setting these values using JS seems inefficient to me. Ideal situation would be if I could make an AJAX call with the selected payement method and this call would return the HTML which I can use to replace the old summary.
Is it bad to render a partialview to HTML on the server and return it using JSON? What is best practice for this situation?

I have an example here:
Javascript
$("#divForPartialView").load("/HelloWorld/GetAwesomePartialView",
{ param1: "hello", param2: 22}, function () {
//do other cool client side stuff
});
Controller Action
public ActionResult GetAwesomePartialView(string param1, int param2)
{
//do some database magic
CustomDTO dto = DAL.GetData(param1, param2);
return PartialView("AwesomePartialView",dto);
}

In your action method return a PartialView([view name]).
Then you can do this with jquery:
var req = $.ajax({
type:"GET",//or "POST" or whatever
url:"[action method url]"
}).success(function(responseData){
$('targetelement').append($(responseData));});
Where 'targetelement' is a selector for the element into which you want to inject the content.
You might want to do $('targetelement').html(''); first before appending the response to the target element.
Update
Or, better yet, use .load from Rick's answer.

Related

MVC4 Ajax forms: How to display server side validation

I am using #Ajax.BeginForm helper method, which submits form data to the server by Ajax. When the data arrive to the server, some server side validation is processed and final result is passed back to the browser.
My problem is, I want the errors to be displayed without page refresh. I have found plenty of questions based on this but they are old. I am wondering if there is some new way how to achieve this. The best way I have found so far is to process the result using jQuery. But maybe in new MVC4 there is some built in functionality how to achieve this problem in a better way?
Your view should look similar to this:
<div id="update-this">
#using (Ajax.BeginForm("YourAction", new AjaxOptions { UpdateTargetId = 'update-this' }))
{
}
</div>
Also use #Html.ValidationMessageFor(model => model.someField) next to your fields to display the error message.
On server side return a partial view if there was any error:
public ActionResult YourAction(YourModel yourmodel)
{
if (ModelState.IsValid)
{
// Do what is needed if the data is valid and return something
}
return PartialView("DisplayPartial", yourmodel);
}
And use Data Annotations on your model to make it work. (Tutorial here.)

How to call Controller Action on standart html event in Asp.Net MVC?

Common question is: how to call Controller.Action and send it some parameters on standard html event (like onblur or onclick).
I`m using Asp.Net MVC3.
Original situation:
I have DropDownList on my page like this:
#Html.DropDownList("DropDownList", ViewBag.selectList as IEnumerable<SelectListItem>)
I dont want to use #Html.DropDownListFor because it means I should save some additional information in my model which is unlikely.
What I need: to call DropDownListSelectionChanged(int moduleId) action of the same controller SelectedIndexChanged event and to send Selected Item Value to this action.
Please, help.
It's pretty simple. You can either use the built in Ajax.BeginForm in MVC land, or you can use jQuery to send the request. I'll show you the jQuery example (simply because jQuery makes ajax stupidly easy and it's easy to write):
$('#myDropDownIdAttribute').change(function()
{
$.ajax({
url: 'Some/ActionName', // SomeController, ActionName
data: { selectedValue: $(this).val() },
success: function()
{
// Success Callback
}
});
});
Then your action method would look like this:
public ActionResult ActionName(string selectedValue)
{
// Do Stuff
}

fill DropdownList from xml using ajax

I have on one page a dropdownlist which I would like to use AJAX in order to populate it from a XML file. Is there a way to tell AJAX to run only certain asp.net method without using WebServices? Any other solution is welcome but the only restriction is that it would be made on the server side (and not with js for example)?
thanks!
This is possible through a variety of means - one approach is to use jQuery on the client-side to generate the AJAX request like so (binding to the page ready here, but it could be bound to the SELECT change event):
$(document).ready( function () {
$.get('/target-url.aspx?someparam=somevalue', function(data) {
// process the returned data - dependant on the format - assuming JSON here.
var items = data['items'];
// may wish to clear the contents of the SELECT box.
// spin through and add OPTION elements
for(var i = 0; i < items.length; i++) {
$('#selectid').append('<option>'+items[i]+'</option>');
}
}
}
Where selectid is the ID of the dropdownlist element (use the ClientId if in ASP.NET).
Then you need to write some code in ASP.NET to respond to the AJAX request with your desired logic.
Some useful links:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/append/
See here for an example of using jQuery and ASP.NET with JSON:
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

jQuery-AJAX to rebind dropdown list to results from stored procedure

I have a dropdown list of peoples names that is quite long. As many as 2,000 names. I would like to make it easier to find the name the user is interested in by limiting the dropdown list to a subset of names at a time. I have done this by creating a series of 26 links (A, B, C ... Z) that call a method in the code behind that populates the dropdown list with only those names starting with the letter the user clicked.
This all works well but I would like to be able to use AJAX to accomplish this update of the dropdown list without a page refresh. I would like to use jQuery for the AJAX functionality rather than ASP.NET AJAX.
My problem is I am not sure how to execute the stored procedure and then "rebind" the dropdown list with the new dataset via jQuery AJAX. Any suggestions or resources that might provide and example or walk-through? Thank you.
Some direction for you.
First create a page, webservice, or httphandler that will take your post and return back json.
Handler:
public void GetNames(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
var results = DataAccess.GetNames(context.Request["letter"]);
string json = //encode results to json somehow, json.net for example.
context.Response.Write(json );
}
The Markup
<ul>
<li>A</li>
</ul>
<select id="names">
</select>
The Script to do a $.post
$(function(){
$("li").click(function(){
var letter = $(this).text();
$.post("SomeUrl/GetNames", {letter: letter}, function(data){
var $sel = $("#names").empty();
$.each(data, function(){
//this assumes the json is an array in the format of {value: 1, name:'joe'}
$sel.append("<option value='" + this.value + "'>" + this.name+ "</option>");
});
}, "json");
});
});
That should be a good outline on how to accomplish your task.
Some additional resources.
jQuery AJAX Tutorial
Intro to JSON on msdn
json.net
jQuery Docs
Creating a http handler that returns json (other articles on the blog could be of use as well)
The jQuery Autocomplete plugin might be a valid solution for you.

ASP.NET MVC Submitting Form Using ActionLink

I am trying to use link to submit a form using the following code:
function deleteItem(formId) {
// submit the form
$("#" + formId).submit();
}
Basically I have a grid and it displays a number of items. Each row has a delete button which deletes the item. I then fire the following function to remove the item from the grid.
function onItemDeleted(name) {
$("#" + name).remove();
}
It works fine when I use a submit button but when I use action link the JavaScript from the controller action is returned as string and not executed.
public JavaScriptResult DeleteItem(string name)
{
var isAjaxRequest = Request.IsAjaxRequest();
_stockService.Delete(name);
var script = String.Format("onItemDeleted('{0}')", name);
return JavaScript(script);
}
And here is the HTML code:
<td>
<% using (Ajax.BeginForm("DeleteItem",null, new AjaxOptions() { LoadingElementId = "divLoading", UpdateTargetId = "divDisplay" },new { id="form_"+stock.Name }))
{ %>
<%=Html.Hidden("name", stock.Name)%>
<a id="link_delete" href="#" onclick="deleteItem('form_ABC')">Delete</a>
<% } %>
</td>
My theory is that submit button does alter the response while the action link simply returns whatever is returned from the controller's action. This means when using submit the JavaScript is added to the response and then executed while in case of action link it is simply returned as string.
If that is the case how can someone use action links instead of submit buttons.
UPDATE:
Seems like I need to perform something extra to make the action link to work since it does not fire the onsubmit event.
http://www.devproconnections.com/article/aspnet22/posting-forms-the-ajax-way-in-asp-net-mvc.aspx
My guess is the MS Ajax form knows how to handle a JavaScriptResponse and execute the code whereas your plain old Action link, with no relationship to the AjaxForm, does not. I'm pretty sure the MS ajax library essentially eval()s the response when it sees the content type of javascript being sent back.
Since you have no callback in your deleteItem() method there is no place for the script to go. To fix you'll have to manually eval() the string sent back which is considered a bad practice.
Now I'm not familiar with the MS Ajax library to be certain of any of this but what your doing is possible. I'd do things differently but don't want to answer with a "my way is better" approach ( especially because your blog has helped me before ) but I'd like to show this can be easier.
I'd ditch the form entirely and use unobtrusive javascript to get the behavior you want. IN psuedo jqueryish ( don't know ms ajax ) code:
function bindMyGrid() {
$('.myDeleteLink').onclicksyntax( function() {
//find the td in the row which contains the name and get the text
var nameTdCell = this.findThisCellSibling();
//do an ajax request to your controller
ajax('myUrl/' + nameTdCell.text(), function onSuccessCallback() {
//get the tr row of the name cell and remove it
nameTdCell.parent().remove();
});
});
}
This also gains the benefit of not returning javascript from your controller which some consider breaking the MVC pattern and seperation of concerns. Hope my psuedo code helps.
Try without the UpdateTargetId property in the AjaxOptions (don't specify it)
new AjaxOptions() { LoadingElementId = "divLoading" }
What about just change look of a standard or using some css class? It'll look like a link and you'll avoid some problems you get with anchors - user will be able to click on it by a mouse wheel and open that link in a new tab/window.

Resources