Не может вызвать Response.Redirect внутри статического метода
Здравствуйте, я пытаюсь запустить webmethod с ajax с страницы aspx. в основном я хочу перенаправить на другую страницу aspx с строкой запроса, но я хочу сделать это из <a href>
, beacuse это часть меню jquery.
из того, что я узнал, я могу использовать только ajax для вызова статических web-методов, но я не могу перенаправить свою статическую функцию.
визуальная студия отмечает это в красной строке, говорящей: "ссылка на объект требуется для метода нестатического поля или свойства System.Web.HttpResponse.Redirect(string)"
вот вызов ajax:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
alert("success");
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
здесь находится href:
<a onclick="redirect_to_profile()">Personal Profile</a>
здесь находится web-метод внутри файла personal_profile.aspx
[WebMethod]
public static void redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
HttpResponse.Redirect("personal_profile.aspx?id="+id);
}
Ответы
Ответ 1
Вам нужно будет вернуть сконфигурированный URL-адрес клиенту:
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
return "personal_profile.aspx?id="+id;
}
Затем, используя JavaScript, в функции success
вызова AJAX задайте местоположение:
window.location = res;
Или, возможно:
window.location = res.d;
Ответ 2
Вам нужно, чтобы ваш веб-метод передал идентификатор пользователя, чей профиль вы хотите перенаправить, затем в вашем обратном вызове jQuery установите window.location в путь плюс строку запроса, например:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
// Redirect to personal_profile.aspx passing it the ID we got back from the web method call
window.location = "personal_profile.aspx?id=" + res;
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
[WebMethod]
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
return db.return_id_by_user(user);
}
Ответ 3
Вместо того, чтобы делать HttpResponse.Redirect, вы можете отправить этот URL-адрес, который вы создали для вас Javascript (ответ на вызов ajax), а затем использовать Javascript-код для перенаправления.
Ответ 4
Попробуйте следующее:
function myFun(a) {
var s = null;
var em = document.getElementById(a + 'productno');
if (em != null)
PageMethods.setSession(em.innerText);
window.location.assign("/Product%20Details.aspx");
}