Passing data from Ajax into partial view - asp.net

I have a partial view that when the user clicks a button, some data is passed to the database and the results returned. The results must be displayed in another partial view. The results are obtained using the following Controller method and Ajax script:
public ActionResult GetResultData(Models.SelectedFilterValues selectedFilters)
{
resultData = resultRepository.GetResultData(
selectedFilters.Projects,
selectedFilters.ExperimentTypes,
selectedFilters.StudySet,
selectedFilters.Species,
selectedFilters.Strain,
selectedFilters.Department,
selectedFilters.Location);
return PartialView("Results", resultData);
}
function GetResultData(selectedProjects, selectedExperiments, selectedStudySets, selectedDepartments, selectedLocations, selectedSpecies, selectedStrain) {
$.ajax({
type: "GET",
url: "/Search/GetResultData",
data: { projects: selectedProjects, experimentTypes: selectedExperiments, studySet: selectedStudySets,
department: selectedDepartments, location: selectedLocations, species: selectedSpecies, strain: selectedStrain
},
error: function (data) {
},
success: function (data) {
}
});
}
I keep getting the error when the data is returned into the Ajax method, is this because it is returning a partial view? What I want is for the Ajax method to accept the data, and then for me to pass that data into the new partial view. Is this possible?
Thanks.

I think you are mixing up client-side and server-side logic.
A partial view can contain logic that is executed on the server. Typically you would execute business logic in a Controller, and UI logic in the PartialView. For instance, any markup using Razor is actually executed on the server. The result then is HTML which is sent to the browser.
This HTML may contain client-side (JavaScript) code. So typically you would create a PartialView which contains JavaScript code that calls jQuery methods such as $.ajax(). When it does, it doesn't matter anymore how the JavaScript got to the browser -- as part of a PartialView or not, that doesn't matter. The JS code is executed on the client side, and it calls logic on the server side.
When the Ajax call returns data to the client side, the JS code there can then render the data into a grid, or apply a jQuery template, or do whatever with it that it wants. What it cannot do, is execute server-side PartialView code, because any PartialView has long since executed.

Related

Return spring mvc Model on Ajax response

I am having a controller that return model objects like below
model.addAttribute("list", list);
When i click a button ajax call happens and it is goes to controller executing everything and it returns. But i don't know how to access this model object in my jsp on ajax response. When i use alert for success ajax response , I am just seeing a html kind of page.
Please give me some example or reference to achieve this
Thanks in advance
Please find my sample code snippet
Controller.java
#RequestMapping(value='/ajax' value="POST")
Public #ResponseBody String displayDropdown(MyForm myform,Model model) {
//logic to fetch details from DB
List<String> list = fetchFromDB();
model.addAttribute("list" list);
return "ajaxResponse";
}
My JSP
In a button click, having the below ajax call
$.ajax {
url:'/ajax',
type:'POST',
data: $("#myform").serialize();
success:function(data) {
alert(response);
}
}
I want to get my model from this ajax response and use it in my jsp.
I am not sure, but from JSP all model attribute variables are accessible simply using ${attribute_name}. In your case it is ${list}
Maybe you can use
console.info(model)
I am not sure that you can access response with JSP. JSP is the server side and response you receive when the page is already sent to client. The only thing you can try is to use COOKIES. Set response in cookies and then access it from the server.
Yes You can easily get Model data from controller, simply
#RequestMapping(value='/ajax' value="POST")
Public String displayDropdown(MyForm myform,Model model) {
//logic to fetch details from DB
List<String> list = fetchFromDB();
model.addAttribute("list" list);
return "yourjsppage";
}
$.ajax {
url:'/ajax',
type:'POST',
data: $("#myform").serialize();
success:function(data) {
$("#page-wrapper").html( data );
}
}
page-wrapper is your content div in jsp page. this returns all jsp page including your model. in this scenario it is also useful when you want (partial rendering) not wanting to refresh whole page but targeting specific page.

In MVC, how to determine if partial view response was valid (on the client side)?

I am new to MVC, so hopefully my question will be straight forward. I am thinking of a scenario where the user submits a form (that is a partial view) and it undergoes server validation. I am wondering how I will know the result of the validation on the client side (javascript) after the form is submitted. For example, if validation fails I will obviously want to return the partial view again with validation messages set, but if it passes validation I may not necessarily want to return the partial view. I may want to return a json object with a message or hide a div or something. I want to be able to determine the validation result on the client. Is something like that possible? Or can I approach this a different way?
The tricky part with AJAX is that the client and server both have to agree on what's supposed to come back from the server in any circumstance. You have a few options:
Your server will always return HTML, and jQuery will always replace the editor content with the HTML that comes back. If the model is invalid, you return a PartialView result. If the model is valid, you return a <script> tag that tells the page what it needs to do (e.g. close a dialog, redirect to a different page, whatever). jQuery will automatically run any script it finds in the results when it tries to insert them into the DOM.
Your server will always return a JSON object representing what happened. In this scenario, your client-side javascript code has to be complex enough to take the results and modify your page to match. Under normal circumstances, this will mean that you don't get to take advantage of MVC's validation features.
Same as 2, except that you use a custom utility method to render the partial view you want into a string, and you make that entire string part of the JSON that comes back. The javascript code then just has to be smart enough to check whether the JSON shows a valid or invalid result, and if the result is valid, replace the contents of your editor area with the partialview HTML that is returned as part of the JSON object you got back.
Same as 3, except you develop an event-based architecture where all your AJAX requests will always expect to get back a JSON object with one or more "events" in it. The AJAX code can then be consolidated into one method that hands the events off to an Event Bus. The event bus then passes the event information into callbacks that have "subscribed" to these events. That way, depending on what kind of events you return from the server, you can have different actions occur on the client side. This strategy requires a lot more up-front work to put in place, but once it's done you can have a lot more flexibility, and the client-side code becomes vastly more maintainable.
Partial views would not have a Layout page. You may use this code to check if the view is rendered as partial view.
#if (String.IsNullOrWhiteSpace(Layout))
{
// Do somthing if it is partial view
}
else
{
// Do somthing if it is full page view
}
If you are using the MVC Data Annotations for validating your Model, then the controller will have a property called ModelState (typeof(ModelStateDictionary) which as a property of IsValid to determine if your Model passed into the Controller/Action is valid.
With IsValid you can return a Json object that can tell your Javascript what to do next.
Update
Here is a really basic example (USES jQuery):
[SomeController.cs]
public class SomeController : Controller
{
public ActionResult ShowForm()
{
return View();
}
public ActionResult ValidateForm(MyFormModel FormModel)
{
FormValidationResults result = new FormValidationResults();
result.IsValid = ModelState.IsValid;
if (result.IsValid)
{
result.RedirectToUrl = "/Controller/Action";
}
this.Json(result);
}
}
[FormValidationResult.cs]
public class FormValidationResults
{
public bool IsValid { get; set; }
public string RedirectToUrl { get; set; }
}
[View.js]
$(document).ready(function()
{
$("#button").click(function()
{
var form = $("#myForm");
$.ajax(
{
url: '/Some/ValidateForm',
type: 'POST',
data: form.serialize(),
success: function(jsonResult)
{
if (jsonResult.IsValid)
{
window.location = jsonResult.RedirectToUrl;
}
}
});
});
});

Multiple submit buttons on same view using different action methods

I am using ASP.NET MVC 3.
I have a view that accepts a view model of type EditGrantApplicationViewModel. In this view model I have properties. When the view is loaded for the first time I pass it an instance of this view model:
public ActionResult Create()
{
EditGrantApplicationViewModel viewModel = new EditGrantApplicationViewModel();
return View(viewModel);
}
On this view I have my submit button that takes the form values and adds it to the database. I also have another button on this view, but it doesn't have to be clicked, and when clicked, it takes the employee number, does a database lookup and gets the employee's details. This data is returned to te same view and prepopulates this view with the data so that the user doesn't have to type in the data. The data can either be retrieved this way or can be manually entered.
Then the user can go on and type in the other fields and edit any of the fields that were returned from the lookup. When doen then the user can click submit to add it to the database. How would I do something like this? Would I require to forms on my page, one going to the Create action method and the other going to GetEmployee action method to do the database lookup? Should I use multiple form on my page? If so is having multiple forms a best practice? Any code samples would be appreciated :)
You can use jquery to fire an AJAX call to return some JSON data when you click a button:
$("someButton").click(function() {
$.ajax({
url: "/Service/GetData",
data: {}, // pass data here
dataType: "json",
type: "POST",
success: function() {
// manipulated return JSON data here
}
});
});
You could have a controller that calls the service and returns JSON or have the service do it and skip the controller. If you do it in a controller:
public ActionResult GetData() {
var someData = service.GetData();
return Json(someData);
}
Assuming the employee details are part of the EditGrantApplicationViewModel you should be able to just populate the fields on the form with the results of the web service call. Basically it should work just like a user manually entering the values. As long as your fields are named correctly the model binder will pick it up.
I'm making an assumption that your web service call is an asynch call from the page using javascript.

jQuery-AJAX calling ASP.NET page method. How to return value back to jQuery?

If I use jQuery AJAX to call a specific ASP.NET page method how to have that method return a value back to the AJAX method that called it?
Update
My situation is I have an existing web application with many existing methods. I would like to be able to use jQuery to execute some of these methods and then update the UI with the results. My mandate is to stay away from ASP.NET AJAX and stick with jQuery. Management is concerned about continued development and support with ASP.NET AJAX from Microsoft. I agree with them.
You can use JQuery with page methods this way: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
HTH.
There are two ways to skin this cat (that I am familiar with).
The ".Net Way" which involves a Web Method and a Script Manager (see here: http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx).
The "Old Skool Way" which involves simply writing a response out by determining what was called. Typically you'd use a framework like MVC so going to http://www.MyWebsite.com/Object/Method/Id can map back to Object.Method(id).
You can do this without a framework like MVC but it makes things a little more difficult and, if you go that route, you should really use an ASP.Net handler rather than an actual page (since you don't need the Aspx overhead). This is an Ashx file.
With pure ASP.NET (not talking WCF here) I'd go with a handler (ASHX) file, and use JSON as the interchange format. I won't get into the details of JSON (here is a decent start), but the idea is a lightweight handler on the server that generates json text and returns it to the client, which can then use the structure easily in javascript.
This is obviously a simplified example but the gist is the JSON can be data driven from the server and easily consumed by the javascript on the client.
server:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/json";
context.Response.WriteFile("~/myData.json");
}
public bool IsReusable {
get {
return false;
}
}
}
client:
myData =
(function ()
{
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "handler.ashx",
'dataType': "json",
'success': function (data) {
// this code is called when the
// data is returned from the server
json = data;
}
});
return json;
}
)();
alert(myData.MyArray[0].MyProperty);

ASP.NET / JavaScript - Ajax call, how to?

Please be gentle, as I'm still new to web programming and -very- new to Ajax!
I've created a C# function which extracts data from an mssql database, formats it to a json string and returns that. Now I need to make a call from my javascript (jQuery) slider through an aspx page that is related to the C# code file.
I have actually never done anything like this before, from what I could tell by googling I need to use xmlHttpRequest, but how exactly do I make the function get hold of this string?
It would be awesome if someone had some example code that shows how this works.
The simplest way to do this is to convert your function into an ASHX file that writes the JSON to the HTTP response.
You can then call it using XmlHttpRequest, although you can call it much more easily using jQuery.
You can call it with jQuery like this:
$.get("/YourFile.ashx", function(obj) { ... }, "json");
It's relatively easy with jQuery if you mark the C# function as a [WebMethod] or make it part of a ASP.NET webservice. Both these techniques make it easy to have the response automatically converted into a JSON object by ASP.NET, which makes processing on the client easier (IMHO).
The example below is if the page has a WebMethod named GetData, but it's trivial to change the URL if you create a service.
$.ajax({ url: "somepage.aspx/GetData",
method: "POST", // post is safer, but could also be GET
data: {}, // any data (as a JSON object) you want to pass to the method
success: function() { alert('We did it!'); }
});
On the server:
[WebMethod]
public static object GetData() {
// query the data...
// return as an anonymous object, which ASP.NET converts to JSON
return new { result = ... };
}

Resources