PageMethods or Alternative in Master Page? - c#

I having a problem that seems i can'f find a solution to which is the following:
I have a master page that have a menu, each link in the menu is a LinkButton.
I am required that whenever a user click on a certain link to show a login popup so i used Ajax ModalPopupExtender and i successfully showed the popup.
Now i want to validate the user which means that i will need to input username and password and press login but since i am in a popup it will close because of postback so i suppressed the postback and now i have to do the checking from the Client side so i need to call a server method from a javascript function, i tried using the PageMethods but i keep getting PageMethdos not defined, then i read that it won't work inside master pages or user controls.
Any solution to my problem ?

PageMethods are to be used in aspx pages , not in MasterPage Methods. The only workaround is to create a seperate .asmx WebService and add your Logic in a static function . To Do so , right click on your solution on VS and click on Add New Item, Select WebService.asmx.
in the code behind of the WebService write a static webMethod
[WebMethod]// press alt+shift+f10 after selecting the WebMethod wording to include the library
public static bool CheckLogin (string username, string password){
//Type your method here
return result;//Result should be Boolean
}
Now on your masterPage.master on client side script click event of the link, Post an Ajax Request to the webservice
$.ajax({
type: "POST",
url: "YourWebServiceName.asmx/CheckLogin",
data: '{"Username":"' + $('#username').val() + '","password":"' +
$('#password').val() + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(message) {
alert(message);//will alert 'true'
//DO what you want to do on client side
},
error: function() {
alert(message);//will alert 'false'
//DO what you want to do on client side
}
});
Please let me know if you need any further clarification
Have a nice day :)

One solution is to create a base class for all your pages and put the page method there. For example:
public class CustomBasePage : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static bool ValidateUser(...)
{
bool isValid = false;
...
return isValid;
}
}
Now all you content page should deliver from CustomBasePage instead of Page:
//public partial class Index : System.Web.UI.Page
public partial class Index : CustomBasePage
{
...
}
This way you write the method only once and it is accessible always, so you can depend on it in your master page.

Did you try adding the <base target="_self"> tag in the head of the page. It will make sure that the postback happens in the original page.

Related

DataAnnotations Not working on submit of form of a partial view called with ajax

I have an ajax call
$.ajax({
type: "POST",
data: $("#divInfoRecherche :input").serialize(),
url: '#Url.Action(Action, Controler)',
success: function(resultat) {
$("#tableauResultatRecherche").css("display", "");
$("#tableauResultatRecherche").html(resultat);
$.validator.unobtrusive.parse($('#PartialViewModel'));
}
});
The line $.validator.unobtrusive.parse($('#PartialViewModel')); makes it possible for the client side validation to pop, everything works fine.
Problem is when I click on Submit of the page, the message errors go back to the error of native JavaScript "This field is required" instead of my custom message linked in the model.
Option I think of is add the content of the partial view in the main view and populate it manually so that all the validations are added on Pageload.
But I still ask to see if another option is possible.
https://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
Here is the script to add and call on the div containing the partial view.

Handling multiple forms on a page

I have a page that is mostly informational data (not an input form, overall). And it has a title that can be edited.
Clicking the Edit Title button pops up a modal window where the user can edit the title and hit submit.
Because this form is a very small part of the page, and because I may need other small forms on the same page, I just created a small handler in the controller to handle this one submit.
[HttpPost]
public ActionResult PageTitle(string title)
{
// ... Save new title to the database ...
// I have no PageTitle page, so just redirect back to the source page
return RedirectToAction("Index");
}
This works okay, but I don't like the extra redirect here. A redirect back to the client causes another round trip back to the server.
Is there a more efficient way to handle small forms on a page, where you don't want to resubmit every input element on the page each time?
I don't think there is a convenient way how to avoid the redirection after a post request (without using Ajax).
You can of course return any View:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult ProcessForm1(FormOneData data)
{
// process form
return View("Index");
}
[HttpPost]
public ActionResult ProcessForm2(FormTwoData data)
{
// process form
return View("Index");
}
So the user will get the same page but the problem with this solution is that the url will be different.
You can have one function for GET request, another for POST requests, both with the same URL. But than you would have to figure out how one action method would handle more forms - doable but terrible for maintenance.
And this can get even more complicated if those forms can appear on more than one page.
But actually, it solves one thing. With the redirection you avoid the re-POST dialog that user gets if they press F5 (and sometimes submit the form again by mistake).
As #TiesonT. points out, post/redirect/get is a standard pattern. No, it doesn't seem like the most efficient. But without doing AJAX or something a little more elaborate, there is really no way to postback to a specialized handler and then refresh the page without a redirect.
Was hoping I overlooked something simple but it looks like I did not.
What about sending form data via Ajax as shown below?
#model Models.YourModel
$('form').submit(function (event) {
event.preventDefault();
//Send the values of all form controls within the <form> tags including the token
var formdata = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("ProcessForm", "Controller")',
cache: false,
dataType: "json",
data: formdata,
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data);
}
});
});
You can also use Partial Views in order to use multiple forms or fragment on the same View.

Loading an ASP.Net page inside another ASP.Net page using Ajax

I managed to load a distinct page inside a div in another page using jquery ajax. The problem I am encountering is that when I click a button inside this sub page, it cause a postback to the whole parent page. How can I force it to just refresh the panel it resides in?
One more thing. I am not sure I am doing the right thing, but the parent page has its own form with runat=server settings, while the secondary page that is loaded inside the div has its own form. I cannot remove the form from the latter because it causes an error.
I have seen some asp.net ajax tutorials but they do not deal with loading sub pages that havbe their own .net controls. Can anyone guide me to some good tutorial?
Thanks!
You need to create a empty with an Id for example : ajaxDiv
Then you create a jquery script like this :
<script type="text/javascript">
// Called at the loading of a page
$(document).ready(function () {
//here you execute an ajax function
$.ajax({
url: 'the url to retrieve data as string ex : /Webservice/Test',
type: 'get',
async: true of false,
//if the request is successful, you load the content of your div with the strings you loaded
success: function (data) {
$("ajaxDiv").html(data);
}
});
});
</script>
the tips is to load your page into the ajax request.
OK, since you are using jQuery, let's set up that event manipulation.
I assume the following markup:
<button type="submit" id="mySubmitButtonId">Submit</button>
Then, on my page I have the following javascript:
$("#mySubmitButtonId").click(function(event) {
event.preventDefault();
// do here what you want to do instead including refresh of a section via ajax
});

AJAX / Postback Issue

I've been struggling for the whole weekend with unwanted postbacks.
The popup I'm working on has a button that basicaly fires a few stored procedures and then closes the pop up window.
What I wanted to achieve is to have the same result when people hit the X closing buton on the top right.
So, X button = myCloseButton.
For that I've done this.
AJAX.
$(window).unload(function(){
var dataToSend = { MethodName: 'UpdateR' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
};
$.ajax(options);
});
.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ #region Ajax methods
if (Request.Form["MethodName"] == "UpdateR")
{
UpdateRegister();
return;
}
#endregion
}
}
And then UpdateRegister() executes the code that I want to execute once people leave the page.
So, the problem comes when people hit another(whatever) control inside the pop up page. The page enters the (!IsPostBack) and the AJAX method. That's understandable since I'm saying on .unload do this and that. (I've tried $(window).bind('beforeunload', function() and it's not working for the desired purpose)
Any idea on "How can I tell the page to difference when it's a closing event like X button or my control, and any other control on the page?" would be much appreciated.
Thanks.
EDIT. It's not something about serializing the form and comparing before leaving. No, it's about logins and stuff, so even if people open the pop up and close it immediately I need to get that.
Why not you create WebMethod and directly call instead of calling via Page_Load() page event.
[WebMethod]
public static string UpdateRegister()
{
// your update register script here
}
Sample call from jquery, you can call this ajax when someone click on load or unload button.
You can call ajax script when button with id "button1" clicked e.g
$(function(){
$('#button1').click(function() {
// close window
window.close();
// call ajax script to perform server side script
$.ajax({
type: "POST",
url: "Sample.aspx/UpdateRegister",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
In case someone gets here with an error something like this:
Answer:
All that was begin a mess in my webform was a button (an asp one). It was postbacking, so I disabled the postback via javascript and that was it. I'm now able to move forward.

Calling FormsAuthentication.SignOut() method using jquery

I am using Asp.Net/C# in my project.I am using Forms Authentication.Currently I call FormsAuthentication.SignOut() on click of Asp.Net button.It works well , but my requirement is that I need to log out a user from horizontal menu option
Logout
That would be Html menu , so how do I call FormsAuthentication.SignOut() method when a user clicks Logout from the menu bar.Is there any solution possible or any other technique.
Any suggestions are welcome.
Thanks
FormsAuthentication.SignOut() is a server side code and you cannot directly invoke it from client side (i.e. browser) - instead, you need to create a URI that will do the same for you.
For example, you can have AJAX service that will call above code or simply speaking, you can have logout.aspx page that will call FormsAuthentication.SignOut() in say page_load. Such a URI can be invoked from jquery to get you what you want.
In your case, you should simply have a link to logout aspx page in your logout menu (or in menu click, write document.location = "/logout.aspx" which essentially means navigating to log-out page).
here you go:
$('#logout').click(function () {
$.ajax({
url: '/logout',
success: function () {
document.location = '/logged_out';
}, error: function () {
alert('Logout failed');
}
});
return false;
});

Categories