ASP NET MVC Server Response to a basic ajax request - asp.net

We have to make an ASP.NET MVC or ASP.NET application for basic ajax navigation in Customer.html of Notrhwind.mdb.
We have this 3 things:
A pure HTML/JavaScript form having HTML input text tags, one for each field of Customers table.
We have also 2 navigation buttons: NextRecord and PrevRecord having at OnClick() event : clientGetRecord(NextOrPrev)
A javascript ajax clientGetRecord function, something like this:
function clientGetRecord(NextOrPrev) {
var oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
var sURL = "ServerGetRecord.aspx?ID=" + NextOrPrev;
oXMLHTTP.open( "POST", sURL, FALSE );
oXMLHTTP.send();
var sResult=oXMLHTTP.responseText;
var aRecord = sResult.split(";");
document.getElementById('CustomerID').value = aRecord[0];
document.getElementById('CompanyName').value = aRecord[1];
document.getElementById('ContactName').value = aRecord[2];
document.getElementById('Adress').value = aRecord[3];
//... and so on ...
};
We must have something like a ServerGetRecord controler function which returns to the clientGetRecord function, a simple string containing the current record fields values separated by comma and using classic ADO database handling.
The question is : How to program and invoke the ServerGetRecord function? Can i have a VB code example of ServerGetRecord function (or ASPX, or ASHX, or something else?..) ?

Don't have any VB smaples for you, but you can create a controller (asp.net mvc) that returns a JsonResult. You get your data from the DB and build the JsonResult object to return.
Then on your client use jQuery to call the controller and get the results as json format.
This post can help you get started: Link
Hope this helps

Related

Invoke server side method using XMLHttpRequest

how can i directly call my own server side function using XMLHttpRequest.
suppose i have one static webmethod in my aspx file then how can i call it by XMLHttpRequest. what header info i need to pass to asp.net engine and as a result asp.net engine can invoke my method and return the response back in the out going stream.
this way i need to call my server side method
<script type="text/javascript">
var request;
// A
// Here is the new function that is called when the user submits the form.
// This example uses POST.
function submitCallback() {
var inputValue = document.getElementById("SearchInput").value;
var sendStr = "name=" + inputValue;
request = new XMLHttpRequest();
// B
// Specify the POST method and send it.
request.open("POST", "Default.aspx/Getdata");
request.onreadystatechange = readyCallback;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("IsLookup", "true");
request.send(sendStr);
}
</script>
please guide me....thanks
I believe you are probably referring to ASP.NET Page Methods when you say One static webmethod in my aspx file. ASP.NET page methods (or web services for consumption in JS) uses JSON serialization for i/p and o/p. So you need to set JSON as the content type for the request and actually send the JSON string in the body i.e.
...
var sendStr = "{name:" + inputValue + "}";
...
request.setRequestHeader("Content-Type", "application/json");
...
request.send(sendStr);
Further, I will suggest you to use jquery or ASP.NET generated proxies (by ScriptManager) instead of directly coding against XmlHttpRequest. See this article for how to use jquery for calling Page methods.
I think, the easiest way will be usage of jQuery for ajax requests: http://api.jquery.com/category/ajax/

MVC ViewData not rendering in View

I have the following code in my post action method for Edit.
JobCardService.Update(viewData.JobCard);
var js = new JavaScriptSerializer();
ViewData["Notifications"] = js.Serialize(new {NoteificationType = "Success", Message = "The installtion was successfully updated"});
return RedirectToAction("Index");
However, on the client, ViewData is null/empty, i.e. this client code
var notifications = eval("<%= ViewData["Notifications"]%>");
renders as
var notifications = eval("");
I'm sure I'm doing something small wrong.
ProfK - I think (as you'll no doubt be aware) you'll have to parse that json result in javascript once you get into your index view via the redirect. the jquery .getJson() method would seem most appropriate: http://api.jquery.com/jQuery.getJSON/
Also, as you're doing a RedirectToAction, then the context of the ViewData will be lost. In that case, you want to use TempData as a drop in replacement. Below is an example of what you could try:
jim
[edit] - not sure if this would work:
// in the controller
TempData["Notifications"] = js.Serialize(...);
// in the index view
function getMyJsondata() {
var json = $.getJson('<%=ViewContext.TempData["Notifications"] %>');
}
or as per your amendment to the question, try this:
// alternative in index view
eval("(" + "<%= TempData['Notifications']%>" + ")");
give it a go...
adendum:
to quote from a previous SO question on Tempdata vs ViewData: What is TempData collection used for in asp.net MVC?
TempData is used to share data between
controller actions. If your controller
does a RedirectToAction and the target
action needs data (perhaps a
particular model instance) to act
upon, you can store this data in
TempData. Using TempData is similar to
storing it in the session, but only
for one round-trip. You use TempData
when you need to pass data to another
controller action rather than a view
for rendering.

Find a control by String from asp.net Web service

Well since it seems relatively difficult to send the object of a WebControl over JSON using jquery.ajax() I've decided to send the name of the control as a string because I know how to do that. Then I promptly realized that, from a web service, I don't actually know how to search for a control by ID name. Since its a service I can't seem to get Control.FindControl() to work so does anyone have ideas or suggestions? All I'm trying to do is call a databind() on my radcombobox.
Thanks in advance!
For any of you that knows anything about asp.net/rad controls - I'm basically updating a database and want the radcombobox to be in sync with that database again after adding something, before I autoselect what was just added. Other than databind do i have to call anything to refresh that list?
Thanks again!
The way i would go in this case is the following:
Make some change on the data set
Make a call to the web service to update the html page
On the service method - i would load the same control and data bind it with the updated data set like this:
// create standard webform
Page page = new Page();
HtmlForm form = new HtmlForm();
page.Controls.Add(form);
// prepare for rendering
StringBuilder html = new StringBuilder();
StringWriter tw = new StringWriter(html);
HtmlTextWriter hw = new HtmlTextWriter(tw);
// load the control to render
Control control = page.LoadControl("relativeControlPath");
TypeOfYourControl myControl = (TypeOfYourControl)control;
myControl.DataSet = GetUpdatedDataSet();
myControl.DataBind();
form.Controls.Add(myControl);
// render
HttpContext.Current.Server.Execute(page, hw, false);
// pack the output as JSON
result.Add("html", html.ToString());
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(result);
return json;
4. When the ajax call receives a response from the previous step, all i have to do i s to replace the current dom element with the newly rendered one:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "webServiceUrl",
data: "{'if you need a specific params to identify nature of your control':'" + data + "'}",
dataType: 'json',
success: function(result) {
var output = eval('(' + result.d + ')');
$("oldNode").remove();
$("parentNode").append(output.html);
}
});
This approach is generally suitable when you are dealing with composite controls and cannot control or change their behavior.
But for general async update methods i would recommend more lightweight methods like sending serialized data over JSON and using something like jQuery templates on client side for markup generation.

Passing flash variables to asp.net

I don't know much about Flash but we are working on a site that has a flash form and when the users pick an option, like selecting a value from a drop down list, we need the value to be passed to asp.net server-side code. What's the easiest way to do this?
Flash can invoke server side service. So use GET or POST to pass data
You could explore these options:
1) Communicate between the SWF and the containing page through JavaScript
2) Communicate via asp.net webservices from the SWF directly to the webservice.
3) Not sure but could probably do a POST to a processing aspx page?
HTH
I think a good option is to use the XML class so consider this:
var xmlRequest = new XML();
xmlRequest.onLoad = parseXMLResponse;
xmlRequest.load("http://yourpathtoyourserver/file.aspx?listselectedvalue=something");
function parseXMLRequest(loaded)
{
trace("hi");
}
You can also have the page give you data back this way so it's not just one way communication.
Assuming you are using Action Script 2.
Read the important notes at the bottom of each codes pertain to sending and retrieving data from flash to .net page. Explanation of the code is in the comment inside the code.
Flash Part (Action Script 2)
//function to send collected form data to asp.net page
//use other control/button to call this function
//important: in order for the 'onLoad' event to work correctly, this function has to be 'Void'
function sendForm():Void
{
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you for filling up the form!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "The form you are trying to fill up has an error!";
}
}
//this is the collected data from the form
lv_out.userName = txtUserName.text;
lv_out.userAddress = txtUserAddress.text;
lv_out.userBirthday = txtUserBirthday.text;
//begin invoke .net page
lv_out.sendAndLoad("ProcessDataForm.aspx", lv_in, "POST");
}
Important note:
The function that contain onLoad event, in this case sendForm function, has to be Void function, meaning it's not returning value. If this function return value, what happen is the function will be executed all the way without waiting for the returned data from .net page, thus the onLoad event will not be set properly.
.Net Part
public void ProcessData
{
//process the data here
Response.Write("status=processed&");
}
Important note:
To send data/message back to flash, you can use Response.Write. However, if you want Action Script to parse the posted message/data from .Net page keep in mind you have to include & symbol at the end of the message. When parsing data/message, Action Script will stop at & symbol, thus leave the rest of the message alone and only get the message under sent variable.

ASP.NET & Ajax: query string parameters using ISO-8859-1 encoding

Here's another one for you to help me solve: I have an ASP.NET website that uses AJAX (asynchronous) calls to am .ashx handler, passing a query string parameter to get some information from the database.
Here's an example of how it works:
Client-side (Javascript) code snippet that makes the asynchronous call to the handler:
/* Capture selected value from a DropDownBox */
var dropdown = document.getElementById(DropDownID);
var selectedValue = dropdown.options[dropdown.selectedIndex].value;
/* Make the call to the handler */
var url = "MyHandler.ashx?param=" + selectedValue;
var ajaxObj = new Ajax();
ajaxObj.doRequest(url, MyCallback, args, connectionFailed);
When I load the webform (that contains this AJAX call) for the first time, it sends the right query string to the handler (I checked it using debug in Visual Studio), like param = Street Joseph Blíss. That's the right behavior I want it to have.
The thing is that when I load that webform again (and all subsequent times), that í character from "Blíss" appears in server-side as í-. As that's the key from the entity I'm trying to select on server-side database access script, it doesn't work as it worked on 1st webform load.
I tried encoding the query string on client-side and decoding it on server-side, using something like this:
Client-side (Javascript):
var encodedParam = encodeURIComponent(selectedValue);
/* Make the call to the handler */
var url = "MyHandler.ashx?param=" + encodedParam ;
Server-side (ASP.NET, C#):
string encodedParam = context.Request.QueryString["param"];
string value = HttpUtility.UrlDecode(encodedParam, Encoding.ASCII);
...but I had no luck with it and the problem still remains. Any help?
After some more searching, I found out how to solve with server-side code refinement. Here's the deal:
I had to alter my .ashx handler to parse the original parameter grabbed from the query string and convert it into UTF-8. Here's how it's made:
// original parameterized value with invalid characters
string paramQs = context.Request.QueryString["param"];
// correct parsed value from query string parameter
string param = Encoding.UTF8.GetString(Encoding.GetEncoding("iso8859-1").GetBytes(paramQs));
Happy coding, folks! :)

Resources