How can i change page in browser, after end of controller?
I tryed this:
Html/JS code:
<form>
<button type="submit" onclick="abc()">123</button>
</form>
<script>
function abc()
{
$.post("/", "abc", function () {
});
}
</script>
ASP.NET MVC Code:
[HttpPost]
public ActionResult Index(dynamic response)
{
return Redirect(Request.UrlReferrer.ToString() + "/Home/OtherPage");
}
What am I doing wrong?
[HttpPost]
public ActionResult Index(dynamic response)
{
return RedirectToAction("OtherPage", "Home");
}
Check this solution -
Your Action should be like this -
public ActionResult RedirectMe()
{
return new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
When you Click the button, you will be redirected to the Google. You have to make sure you construct a proper URL (instead of google) and send it back.
If you want to pass some parameters to Action, then follow this way -
public ActionResult RedirectMe(string id)
{
return new JsonResult(){ Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
Finally your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: "This is my parameter"}),
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
If you want to redirect to another page in your client code, You may send the new url in a JSON response and use window.location.href property to naviagate to that.
[HttpPost]
public ActionResult Index(dynamic response)
{
//Do your other work
string newUrl=Request.UrlReferrer.ToString() + "/Home/OtherPage";
//It may be better to use the Helper methods to get the url.
return Json(new { NewUrl=newUrl);
}
In your ajax call
$.post("YourURLHEre",{ response :YourDataHere},function(res){
window.location.href=res;
});
Related
I want to post with AJAX a string array with some data to my controller. It's just plain text, and my controller is always receiving a null parameter. I understand i shouldn't stringify since i don't use a model or viewmodel.
I searched other questions but most refer to forms and use viewmodel properties.
Here is my code:
Controller
[HttpPost]
public ActionResult FirstAjax(string[] listValues)
{
//TODO
return Json("Reached the controller", JsonRequestBehavior.AllowGet);
}
I added that JSON return to check if I was actually hitting the controller and I receive the message on my view.
AJAX POST
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: listValues,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
Since my list is sortable with drag & drop, the listValues is filled with the text value of the <li> items in the order when the button is clicked.
View
<div class="demo">
<ul id="sortable">
<li class="ui-state-default">Cat</li>
<li class="ui-state-default">Dog</li>
<li class="ui-state-default">Tiger</li>
</ul>
<button type="button" onclick="display_array();">Ajax Post!</button>
</div><!-- End demo -->
Write your Ajax POST method as follows:
$(document).ready(function(){
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: {listValues: listValues},
contentType: 'application/json'
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
Hope this will solve your problem.
Change your ajax options to:
$.ajax({
...
data: {listValues: listValues},
...
});
the reason is: server is expecting a posted object/query string that's same naming with parameters. the data is converted to listValues=...&otherParams=... in query string. if you post an array without specifying parameter name, JQuery cannot map them correctly
You need contentType as application/json and use JSON.stringify to convert JavaScript object to JSON string.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serviceURL,
data: JSON.stringify({ listValues: listValues}),
success: successFunc,
error: errorFunc
});
Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.
i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>
I have function on .cs page
[System.Web.Services.WebMethod]
public static string getdata()
{
ProductBAL objbal = new ProductBAL(); // Calling class
int i = 0;
i = objbal.get_last_orderid(); //Select query
i = i + 1;
ProductDAL objdal = new ProductDAL(); // Calling class
objdal.insert_new_orderid(i); //Insert query
HttpCookie orderid = new HttpCookie("orderid");
orderid.Value = "MP_" + Convert.ToString(i);
Response.Cookies.Add(orderid);
Response.Cookies["orderid"].Expires = DateTime.Now.AddHours(5);
string abc=Convert.ToString(i);
return abc;
}
My Html page code is
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>calling function from .cs</title>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
$.ajax({ type: "GET", url: "default.aspx/getdata()", success: function (data) { });
alert("Done");
}
</script>
</head>
<body>
<form name="ecom" method="post" action="https://www.google.co.in/">
<input id="Submit1" type="submit" name="submit" runat="server" value="Submit" onclick="return Submit1_onclick()">
</form>
</body>
I am trying to call my web side function to client side on submit click.
Am I missing something? Please give a demo from my above code
function Submit1_onclick() {
// alert("Hello");
$.ajax({
type: "GET",
url: 'demo.aspx/getdata',
data: "{}",
//"{character:'M'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
//alert("success");
alert("This is ajax call:");
},
error: function() {
//alert(Error);
alert("something went wrong");
}
});
// alert("Done");
}
[WebMethod()] //U have to declare this method as a web method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string getdata()
{
On your url try : "PageName.aspx/MethodName". Also check out this blog post by Dave Ward :
Using jQuery to directly call ASP.NET AJAX page methods
Below line is error prone. do not include "()" in url method name.
$.ajax({ type: "GET", url: "/getdata()", success: function (data) { });
Replace above line with
$.ajax({ type: "GET", url: "/getdata", success: function (data) { });
See the following working example
// Code behind method declared static
[WebMethod]
public static string GetSquare(String value)
{
return "hello" + value;
}
your button whose click this has to be done
<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" />
script for this
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSquare",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "test" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
From your comments I have gathered that you are verifying if this method is working by checking for new entries in a database table. The data in the database could be missing for other reasons rather than the query. To verify, try a more simple web method, and go from there.
eg,
Html :
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitClick();" />
Javascript :
function submitClick() {
$.ajax({
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "default.aspx/getdata",
success: function (data) {
console.log(data);
alert("success" + data);
},
error: function () {
alert("something went wrong");
}
});
return false; // Note: the return false will prevent postback
}
C#
[System.Web.Services.WebMethod]
public static string getdata()
{
return "Hello World!";
}
If you do not see a success response, then the problem is indeed with your javascript, or rather with the site setup which is somehow preventing callbacks from javascript.
If the method succeeds then it is likely that your database insertion script is raising an error and you should step through it to see that cause.
I am pulling my hair. For the love of my life I cannot make this work. I have a form in my view:
<div id="cancel" class="cancel">
<form method="post" class="cancelForm">
<input type="hidden" class="cancelId" name="cancelId" value="#appliedLvl.LeavesId" />
<input id="cancelMe" class="cancelMe" type="submit" value="Cancel"/>
</form>
</div>
The javascript
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});
And the Controller
[HttpPost]
public ActionResult Cancel(Guid cancelId )
{
//do stuff here
return PartialView();
}
I always get into the error function of the ajax. No matter what I have tried. This same javascript code works perfectly on my php projects. Don't know what is wrong here. Thanks in advace for any help.
Edit
The error here was the fact that I was expecting in the Action a Guid not a string!
You aren't passing in a cancelId parameter, so it isn't seeing your controller method.
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
data: { cancelId = MYcancelId },
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});