Find a control by String from asp.net Web service - asp.net

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.

Related

KendoUI : data-bind not fully working

I created this sample locally
http://demos.telerik.com/kendo-ui/mvvm/remote-binding
In my 'update' transport, I did modify the 'ProductName' from my WebAPI
public IHttpActionResult Update(Product prod)
{
prod.Price = prod.UnitPrice * prod.Quantity;
prod.ProductName = prod.ProductName + DateTime.Now.ToString();
return Ok(prod);
}
It did update and reflect on my 'dropdownlist'.
The issue is the textbox id=products is not showing the latest productname. The textbox is binded using
data-bind="value: selectedProduct.ProductName"
How can I refresh this text box ?
Thank you.
All is same except this
update: {
url: "/Product/Update",
contentType: "application/json",
type: "POST"
},
and this.
parameterMap: function (data, type) {
return kendo.stringify(data);
}
If these changes are not made; my webapi will not receive any value.
I notice like the binding somehow got broken momentarily; is it because its indirectly reference using the var 'selectedProduct' ?
The reason, I believe, that your textbox is not updating is because of two reasons: 1) you're changing the data on the server instead of the client, and 2) the textbox is tied to the selectedProduct variable which is in no way tied to the data source.
In other words, when you submit the update, because your dropdown list is bound to the productSource data source, it's data gets updated automatically and the list is refreshed to show you the changes. This is expected. On the other hand, selectedProduct is not tied to the data source in any way, so, it still holds the old value before the update was called.
The solution is you have to manually update selectedProduct after the update request returns.

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.

Gridview manipulation using JQuery and JavaScript

I have an ASP.NET gridview I want to manipulate using JavaScript/JQuery. The problem I THINK I'm going to have with my approach is that the server won't have any knowledge of the rows that I am appending via gridview since the html representation of the gridview control is coupled with the object model that lives on the server. So here is what I need to do:
I need to append to the gridview when a user submits data, and submit each row in the batch of entered data to the server to be processed. Because I have other ASP.NET controls that will contain data that I want to submit, I'd like to submit all that data via a traditional postback to the server.
How do I implement this approach if possible?
If not possible, could you please explain?
Thank you very much for your help.
var queryString = "";
// This could be based on a number of different events
$('#finishButton').click(function(){
// Iterate through each input (you could add other form elements)
$('#myForm input').each(function(){
// Build your query string to post to your aspx page
queryString += $(this).attr("name") + "&" + $(this).val() + ",";
});
});
// Make sure special chars are escaped
queryString = escape(queryString);
// POST the form to your aspx page
$.ajax({
type: 'POST',
url: 'myFormProcessor.aspx',
data: queryString,
// Upon a successful POST, successHandler will be called
success: successHandler
});
// Add the new data to the grid
function successHandler(){
// Clone the last row
$('#myTable tr:last').clone(true).insertAfter('#myTable tr:last');
// Here you could just break apart the query
// string you build in the above code
// and use those values to change the values
// in the row you added to the grid
}
Make sure to unescape the query string in your aspx page, and then break it up by the delimiters you're using. I used '&' to separate key/value and commas between variables (inputs).

Localize javascript messages and validation text

I'm working on a web project that is multilingual. For example, one portion of the project involves some custom google mapping that utilizes a client-side interace using jquery/.net to add points to a map and save them to the database.
There will be some validation and other informational messaging (ex. 'Please add at least one point to the map') that will have to be localized.
The only options I can think of right now are:
Use a code render block in the javascript to pull in the localized message from a resource file
Use hidden fields with meta:resourcekey to automatically grab the proper localized message from the resource file using the current culture, and get the .val() in jquery when necessary.
Make a webservice call to get the correct message by key/language each time a message is required.
Any thoughts, experiences?
EDIT:
I'd prefer to use the .net resource files to keep things consistent with the rest of the application.
Ok, I built a generic web service to allow me to grab resources and return them in a dictionary (probably a better way to convert to the dictionary)...
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=True)> _
Public Function GetResources(ByVal resourceFileName As String, ByVal culture As String) As Dictionary(Of String, String)
Dim reader As New System.Resources.ResXResourceReader(String.Format(Server.MapPath("/App_GlobalResources/{0}.{1}.resx"), resourceFileName, culture))
If reader IsNot Nothing Then
Dim d As New Dictionary(Of String, String)
Dim enumerator As System.Collections.IDictionaryEnumerator = reader.GetEnumerator()
While enumerator.MoveNext
d.Add(enumerator.Key, enumerator.Value)
End While
Return d
End If
Return Nothing
End Function
Then, I can grab this json result and assign it to a local variable:
// load resources
$.ajax({
type: "POST",
url: "mapping.asmx/GetResources",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"resourceFileName":"common","culture":"en-CA"}',
cache: true,
async: false,
success: function(data) {
localizations = data.d;
}
});
Then, you can grab your value from the local variable like so:
localizations.Key1
The only catch here is that if you want to assign the localizations to a global variable you have to run it async=false, otherwise you won't have the translations available when you need them. I'm trying to use 'get' so I can cache the response, but it's not working for me. See this question:
Can't return Dictionary(Of String, String) via GET ajax web request, works with POST
I've done this before where there are hidden fields that have their values set on Page_Init() and Page_Load() with the appropriate values from the global and local resource files. The javascript code would then work with those hidden values.
Code Behind
this.hfInvalidCheckDateMessage.Value = this.GetLocalResourceObject("DatesRequired").ToString();
Page.aspx
$('#<%= btnSearch.ClientID %>').click(function(e) {
if (!RequiredFieldCheck()) {
var message = $("#<%= hfInvalidCheckDateMessage.ClientID %>").val();
alert(message);
e.preventDefault();
$("#<%= txtAuthDateFrom.ClientID %>").focus();
}
});
Disclaimer... Not sure if this was the best route or not, but it does seem to work well.
I've implemented a modified version of the solution described here: http://madskristensen.net/post/Localize-text-in-JavaScript-files-in-ASPNET.aspx
I changed it to allow for multiple resource file names, if the need for it arises, by changing the regular expression and by using the HttpContext.GetGlobalResourceObject method to retrieve the resource string.
I use this technique. It makes it easy for anyone with little coding experience to edit the phrase JavaScript file.
var lang = 0 // 0 = english, 1 = french
var phrases=[]
phrases["plans"] = "Rate Plans and Features|Forfaits et options").split("|")
then you output it as:
phrases["plans"][lang]
...add more columns as required.

ASP NET MVC Server Response to a basic ajax request

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

Resources