Push Table to screen - c#

I have an AJAX request when a branch of my JSSTree is clicked
$("#jstree").bind("select_node.jstree", function(evt, data)
{
var idArgument = data.node.text;
$.ajax(
{
type: "POST",
url: "WebForm1.aspx/brancheSelectionnee",
data: JSON.stringify({ id: idArgument }),
contentType: "application/json; charset=utf-8",
success: function(msg)
{
;
}
});
});
So, I call this function, which make a new "page" (because it's static) and call a function that return a System.Web.UI.WebControls.Table.
public static string brancheSelectionnee(string id)
{
var page = (WebForm1)HttpContext.Current.CurrentHandler;
System.Web.UI.WebControls.Table tableau = page.brancheSelectionneeNonStatique(id);
var stringWriter = new StringWriter();
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
tableau.RenderControl(htmlWriter);
}
string tableauString=stringWriter.ToString();
return "randomstring";
}
Big problem here: My "tableau" is updated, with what I want (I see this with the htmlWriter) but.. I don't know how put it in my screen!
I have it in my C# code, but I want it in the screen, and not just here.
I have "tableauArticle" which is a real System.Web.UI.WebControls.Table, in my ASP.net code.
I tried some things, like putting "tableauArticle" as Static, then
tableauArticles = tableau;
But I didn't see any changement. I think that I updated a table in the page that I don't display
I think that the main problem is that my pagee isn't refresh or I do my tables wrong.

You do an AJAX request, so there is no page refresh. You just get a string (with HTML) back from your server method. You then have to manually put that string on your page. This happens in the success callback function which in your code is empty. As first step try something like this:
success: function(msg)
{
$('<div class="newtable">').html(msg).appendTo('body');
}
On the server-side your method brancheSelectionnee needs the AjaxMethod attribute so that it can be called with AJAX:
[Ajax.AjaxMethod()]
public static string brancheSelectionnee(string id)
(It also should return tableauString; not "randomstring", right?. And I am not sure if you can use the HttpContext.Current.CurrentHandler there, but that is for a second step if the basic AJAX stuff works.)
Here is one tutorial for all this which gives you an overview.

For the answer, it is 100% Raidri solution :
$('#tableauArticles').empty();
$('<div class="newtable">').html(msg.d).appendTo('#tableauArticles');

Related

Jquery .post method is sending a null value. How to pass actual value to controller?

I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty

How do I refresh UI on request?

I've a Web app with a button that makes a call to an API to refresh data:
[AcceptVerbs("GET")]
[Route("refreshFromService/{guid}")]
public HttpResponseMessage RefreshDataFromService(string guid)
{
if (!string.IsNullOrEmpty(guid) && guid.Length == 36 && new Guid(guid) == new Guid("C943F8E4-647D-4044-B19E-4D97FA38EDE0"))
{
new AdData().RefreshCacheAdData(true);
new JdeData().RefreshCacheJdeData(true);
return new HttpResponseMessage(HttpStatusCode.OK);
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
Actually, it's an AJAX call, so in my Network Tab in Google Chrome, I see the request is in pending for 5 minutes.
How can I make this method an async method and how can I refresh my UI to show progress?
EDIT
When I refresh the page, I want the Progress Status to be updated.
First of all, it has nothing to do with a backend. So solution to your problem lies on frontend site. Ajax are asynchronous by nature so you can do something like that.
const loader = document.createElement('span')
// some styles for the loader
// i'm using body just for example purposes
document.body.appendChild(loader)
fetch('refreshFromService/{guid}')
.then(data => {
document.body.removeChild(loader)
// do something with data
return data
})
You have to handle it on UI like this:
function getFlag() {
var option = {
url: '/controllerName/actionName',
data: JSON.stringify({}),
method: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8'
};
$.ajax(option).success(function (data) {
$("#picture").append("<img id=\"img1\" src=" + data.img_path + "\ />");
});
};
I am using this code in UI for getting flags at runtime. So you need to write same type of code and get response from the backend.
url: '/controllerName/actionName' is the controller in MVC and then action implemented in that controller.
Request this method in UI with document.ready
I hope I have made sense to you. If still not clear write back i will explain further.
Cheers!

Server result to webpage

I am trying to simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}

Fill jQuery Variable from serverside on load

I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.

Pass a parameter to server method using JavaScript

I have a public in my code behind page that takes a string.
I would like to call this method from javascript.
The parameter that I want to pass down is variable that changes from a ddl.
So I have something like this:
var value = document.getElementById('ddlContact').value;
<%=PopulateContactFields("value") %>
This passes down the word 'value' and not the data in value.
I can't figure out the proper syntax to pass down the data in value.
Thanks
As mentioned by others, trying to access C# code behind directly from javascript is impossible.
However, you can communicate with it indirectly.
I think your best shot is to use a combination of jQuery and the [WebMethod] attribute.
javascript function using jQuery to do an AJAX call:
function Search() {
var search = $('#<%= ddlContact.ClientId %>').val();
var options = {
type: "POST",
url: "Default.aspx/Hello",
data: "{'name' :'" + search + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
};
$.ajax(options);
}
Code behind:
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public void Hello(string name)
{
return "Hi " + name;
}
}
The code you are showing is executed server side when the HTML is generated. In other words it is executed BEFORE it hits the browser and your user had a chance to do anything with the page.
No matter what syntax you would use here the information you want cannot be accessed at this time - it does not exist yet.
The right approach here is to sent this information to the server either by posting the page or using AJAX and then, on the tail end of request/response cycle do your processing
Another option would be to do the processing client side using Javascript

Categories