I call a method in a separate Class file that needs to update a label.
[WebMethod] //needed for the AJAX call
public static void MyClick(int postid, int userid) //must be static
{
Page page = new Page();
//Page page = HttpContext.Current.Handler as Page //Pass the Page but don't work
MyClass.MyMethod(postid, userid, page);
}
The method MyClick() is called from an asp.aspx file (With MasterPage), to a separate MyClass.cs file.
I am not being able to get the Control (Label) with FindControl(). My guess is the "Page" is not being passed correctly. For what i've seen in debug, "page" comes with many exceptions.
((Label)page.FindControl("ContentPlaceHolder1_lbl)).Text = "foo";
This is the sequence:
1) User clicks sort of a "Like" dynamically-created LinkButton
2) There is a JS listener that on click changes to "Dislike" (example) and does an AJAX POST to aspx page method MyClick() with parameters (postid, userid).
3) MyClick() calls MyMethod(postid, userid) that is in MyClass.cs
4) MyMethod() does some SQL (was working) and updates the label (AJAX call not working since MyMethod() tries to set label to "foo").
You're not passing the current page, you're creating a new one:
Page page = new Page();
You could just pass a reference to the current page:
MyClass.MyMethod(postid, userid, this);
(Though in order to do that your page method shouldn't be static. In fact, in order to reference anything on the page instance that method shouldn't be static. See edit below)
However, in general it's best practice not to have other components rely on your page elements. Only the page's code should know/care about the UI elements it owns.
Instead of having the method set the value, have the method compute and return the value and then have the page set it. Something like this:
var result = MyClass.MyMethod(postid, userid);
myLabel.Text = result;
That way the external component isn't tightly coupled to this specific page, can be re-used by other pages, etc.
Edit: What you're trying to do physically won't work in the framework you're using. AJAX-invoked web methods are static for a reason. They don't maintain page state. So in the context of that web method there is no page and there is no label. The AJAX call is a simple service which accepts values and returns a response.
So even if you could update a label server-side, that's not going to do anything client-side. Your client-side code needs to update the markup in the browser. To do that, the AJAX call should simply respond with the new value and the JavaScript code should use that returned value to update the page. Something like this:
[WebMethod]
public static string MyClick(int postid, int userid)
{
return MyClass.MyMethod(postid, userid);
}
As in the earlier part of this answer, that external component should simply calculate and respond with the new value. It should not be coupled to the page. This web method should result in the client-side code receiving the updated value. Then, however you manage that client-side (you have no client-side code in the question), you would update the page markup with that resulting value.
Related
here is the code from my cshtml file
<button type="button" class="button js-book-class" onclick="#Url.Action("BookTheClass", "MemberArea", new { ClassID = Aclass.ClassID })">Book Now</button>
and here my function inside MemberAreaController.cs
[HttpPost]
public ContentResult BookTheClass(int ClassID)
{
Class selectedClass= _context.classes.Find(ClassID);
selectedClass.spaceUsed++;
_context.SaveChanges();
return Content(ClassID.ToString());//just for testing
}
This is because you have conflict.
Url.Action generates a href link, which in click, will execute a browser navigation, which means GET request.
While your server BookTheClass action is expected to be called when executing a POST.
The easy fix which in this case is also the not so good solution, is to change your method to [HttpGet] (which i believe is the default) and it will be resolved.
The more accurate solution, will be to create a form element and making the button submit the data, this will acquire you a change only in HTML and not server side.
The reason i think you should stick to Post, is because i believe in the notion that GET should be consider as a query like, and that identical requests should have the same response.
Whereas Post should have the role of Actions which result in side-effects. which in Rest, means Creation. But as general rule of changing a state in the server as a result.
This is an ASP.NET MVC project. I'm trying to retrieve value from a session and it always returns null.
The SaveToSession & GetFromSession methods are in a separate helper class.
When the submit button is clicked, it makes a call to the controller method and in turn to the helper method to save data in session.
Another anchor tag click (which has the controller path) will hit the same controller which calls the helper method to fetch the data from session. This is where the data is null always.
These are the methods in my helper class
public static void SaveDataInSession(string sessionName, IEnumerable<Item> lstData)
{
System.Web.HttpContext.Current.Session[sessionName] = lstData;
}
public static void GetDataFromSession(string sessionName, out IEnumerable<Item> lstData)
{
lstData = null;
var test = System.Web.HttpContext.Current.Session; //This session has a new SessionID and hence does not have the data.
if (System.Web.HttpContext.Current.Session[sessionName] != null)
{
// it never comes into this block
}
}
During debug, I can see that the data is saved into the session as I can see the session name in the keys list.
The same code worked fine in another ASP.NET MVC project. I checked the web.config file of that project if there were any session related entries and there were none.
UPDATE: I have observed that, when saving the data the session id generated is different and when fetching the data, it has another id. I think this could be the reason, but why is it creating new session Ids when I'm not even refreshing the page. What can be done to fix this.
The System.Web.Mvc version is 5.2.3.0
Can we define a function in one cs page and refer that function in another cs page so that the functions designed in the 2nd cs page is executed with the 1st cs page function?
such like..in 1st cs page
Iwebdriver driver;
driver=new firefoxdriver();
In the 2nd cs page, I have many functions included based on the above function, so how can I refer this as a function in 2nd cs page so that code simplicity will exists?
This is a very badly worded question but I can only assume that essentially what you are trying to achieve is to have the ability to call functions from one test in another test, or rather one class from another class.
This is basic C#.
Your code should be split out in a way that means this is easily achievable. So it means that your tests are totally seperate from your actual logic.
Using Page Objects is one way to go:
http://code.google.com/p/selenium/wiki/PageObjects
This would mean you have a page like:
public class LoginPage
{
public HomePage Login(string username, string password)
{
// do the login stuff
// return the home page
}
}
public class HomePage
{
// some logic related to what the user can see on the home page.
}
You'd call it in a test like:
var loginPage = new LoginPage();
HomePage homePage = loginPage.Login(username, password);
Since it's now seperated, you could call LoginPage.Login() from anywhere.
The key here, is to not bundle all your logic into the tests themselves. As in, don't copy/paste the login code to login to your website into each test. Store it, like the above. The tests should be the steps you take, the page objects should define how those steps are taken. This way you can achieve your goal.
I have a javascript method looks like this
JSMethod(JS_para_1,JS_para_2)
{
......
,,,,,
}
and I have an ASP.NET method like this
ASP_Net_Method(ASP_Para_1,ASP_Para_2)
{
....
,,,
}
Now I want to call this ASP_Net_Method from my JSMethod by passing some parameters over there..
Just to be clear:
Your javascript is executed by the user's browser on the user's laptop
Your ASP.NET method is executed on your server
So, what you probably want to do is to send a message from the browser to the server saying "Hey, run this method and give me the result back".
If you are doing traditional ASP.NET development (not ASP.NET MVC), I think the normal approach would be to create an ASPX page which, when requested, executes the method you want executed. Then, in your javascript you just need to request this page. To do this, you can use jQuery (either jQuery ajax, jQuery get or jQuery post).
You will need to download the jQuery library and include it in your page for this to work.
Give it a go and if you can't get it to work, come back for more specific advice.
EDIT: You can also take a look at ASP.NET AJAX. The home page has a lot of tutorials and videos.
What you really want to do is execute server-side code (sometimes called "Code-behind", which was the term I used when googling this.) from javascript.
This post shows several options. The better ones are toward the bottom.
http://forums.asp.net/t/1059213.aspx
Basically, every function that fires a server side event uses a javascript method called __doPostBack and here is an example of what you want to do.
Ajax's PageMethods is very useful for this if you don't want to do a full postback and just need to call 1 method.
First I decorate a method in my aspx.cs file like so:
[System.Web.Services.WebMethod]
public static string getVersions(string filePath)
{ ...
return myString;
}
Notice the "static" too. Then in javascript I can call this like:
PageMethods.getVersions(_hfFilePath.value, LoadVersionsCallback);
You can have as many parameters as you need of different data types. The last parameter is the JavaScript function that gets called when the call returns. Looks something like:
function LoadVersionsCallback(result) {
...
// I make a drop down list box out of the results:
parts = result.split('|');
for (var i = 0; i < parts.length; i++) {
_ddl.options[_ddl.options.length] =
new Option(parts[i].replace(/~/g, ", "), parts[i]);
}
...
}
Finally, you must have the script managers property "EnablePageMethods" set to "true".
<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1"
runat="server" EnablePageMethods="true"
EnablePartialRendering="true"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">
</ajaxToolkit:ToolkitScriptManager>
So from JavaScript you can call a static function on your page's behind code.
I'm trying to design a view to accept donations, sell memberships, or sell tickets to events.
I have a dropdown list that displays "Make a donation", "Purchase membership", and the subsequent options are populated from the IList<Event> Model passed from the controller. I use javascript to determine which panel (membership, donation, or event) should be displayed based on the selection.
The problem I'm having is that once an event is selected, I need to be able to dynamically populate the Event panel with the properties of the selected event (without, of course, having to put the user through a browser refresh). I was told by someone that I should be able to use Ajax to accomplish this. Supposedly I could go to my server/home/GetEventById action to do this. However, I haven't been able to find any examples or any tutorials that would help me accomplish this.
Could anybody shed some light on this for me by means of how to go about this, or provide examples or tutorials that would help me?
Here is a code example of fetching some content by calling a controller method through ajax, and then populating a jQuery dialog with it. Hopefully this helps point you in the right direction.
The controller method:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetItemsForJson()
{
var items = Repository.GetItems();
var result = Json(items);
return result;
}
And the jQuery to make it happen:
$('#dialog_link').click(function () {
$.getJSON("/Items/GetItemsForJson/", getItems);
});
function getItems(items) {
$("#itemlist").text("");
$.each(items, function (i, item) {
$("#itemlist").append("<li>" + item.Id + item.Name + "</li>");
});
}
Your question is a bit too broad. I assume you already implemented your Action in controller so we concentrate only on client side scripting.
Following should within $.ready:
$("#ddlSelectEvent").change(function() { // this will fire when drop down list is changed
var selection = $(this).attr("selected"); // text representation of selected value
$(".panels").hide();
$("#panel_" + selection).show(); // Assume the panel naming will be panel_MakeDonation and those...
// Now is time for ajax - load html directly
$.get("server/home/geteventbyId",
{id: "12345"},
function (data) { // callback when data is loaded
$("#panel_" + selection).html(data);
}
);
});
Above codes assume you populate content of panel with html. You might use JSON or other types depending on how you implement it.
http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype
I'm not sure how MVC changes this, but here is how I do a callback with Ajax:
In the onchange event of the dropdownlist box you would call a java function that uses Ajax's PageMethod, something like this:
PageMethods.getVersions(LoadVersionsCallback);
The method you are calling in your .aspx.cs file has to be static, it can take parameters and looks something like:
[System.Web.Services.WebMethod]
public static string getVersions() {
StringBuilder sb = new StringBuilder();
... etc.
return sb.ToString();
}
The javascript function that you specified when you called the method will run when the method completes. It will be passed the results.
function LoadVersionsCallback(result) {
// do something with the results - I load a dropdown list box.
...etc.
}