[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(string latitud, string longitud)
{
Session["Latitude"] = latitud;
Session["Longitude"] = longitud;
return RedirectToAction("search?what=&by=bnm");
}
$.ajax({
type: "POST",
async: false,
url: url, // '#Url.Action("mapchanged")',
data: {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
},
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(data) {
alert('Success');
},
error: function(err) {
alert('error = ' + err.status);
}
});
The above code is not working - it's giving error 404. Also tried var url = '"Home/mapchanged/"' but it's also not working. The ajax code is in map.js file.
Do you have a view for that action? Plus it's an ajax post, you can't redirect to another action while doing ajax post. Try to return json from that action and see if it works.
return Json(new { true }, JsonRequestBehavior.AllowGet);
I tried to reproduce source code. It had some issues with current code.
Missed configure for Route attribute at RouteConfig class, without this configure [Route] annotation/attribute not work.
routes.MapMvcAttributeRoutes()
In ajax call did not use JSON.stringify for data
var data = {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
};
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("mapchanged")',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
alert('Success');
window.location.href = data.url;
},
error: function (err) {
alert('error = ' + err.status);
}
});
You should return Json object with url property instead of RedirectToAction
[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(LongLat obj)
{
Session["Latitude"] = obj.latitud;
Session["Longitude"] = obj.longitud;
//return RedirectToAction("search?what=&by=bnm");
return Json(new {url = "search?what=&by=bnm"});
}
public class LongLat
{
public double latitud { get; set; }
public double longitud { get; set; }
}
Related
Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}
I have something that i do not understand .
I do have a global function AjaxPost()
that take url and data than send them to backend .
it calls the function but the parameters are always null .
So i take the same content of the function and used it directly in the request , it works perfectly .
this One Doesn't work //example : AjaxPost("/Road/DeleteRoad", road);
function AjaxPost(url, data) {
return $.ajax({
type: "post",
url: url,
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
}
this one works perfectly
$.ajax({
type: "post",
url: "/Road/DeleteRoad",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(road)
});
Here the action method
[HttpPost]
public async Task<IActionResult> DeleteRoad([FromBody]r road)
{
int.TryParse(road.RoadID, out int RoadID);
if (RoadID > 0)
{
await _road.DeleteRoad(RoadID);
}
return RedirectToAction("Index");
}
Here is the class r
public class r
{
public string RoadID { get; set; }
}
Here Is The Road object
//for example :
var road ={
RoadID :4,
}
Maybe you are not passing the road parameter correctly?
The following code works, sending two calls to the server. The server correctly retrieves the RoadID value. Here's the javascript:
"use strict";
$(document).ready(() => {
var road = { RoadID: 4 };
// First call
$.ajax({
type: "post",
url: "/home/DeleteRoad",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(road)
});
// Second call
ajaxPost("/home/DeleteRoad", road);
}
function ajaxPost(url, data) {
return $.ajax({
type: "post",
url: url,
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
}
The C# code is:
public class Road
{
public string RoadID { get; set; }
}
[HttpPost]
public async Task<ActionResult> DeleteRoad([System.Web.Http.FromBody]Road road)
{
Debug.WriteLine($"Road ID = { road.RoadID }");
return RedirectToAction("Index");
}
The server's output is:
Road ID = 4
Road ID = 4
Hope this helps :)
This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].
I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.
I am trying to submit a object from a form to my mvc controller.
here is the js:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.user = jQuery('#selectUser').val();
model.roleslist = usersRoles;
console.log('model: ' + 'user: ' + model.user + 'roles: ' + model.roleslist);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("
AddUser ")",
dataType: "json",
//data: { model: JSON.stringify(usersRoles) },
data: {
model: JSON.stringify(model)
},
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
now that fetches al the necessary info and builds the object "model" and then posts it to the controller.
Here is my view model:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
Here is my controller:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
How can I receive a json object in the controller? Now currently my model is null when a post is executed by the jquery. This means that it is not binding correctly. I am sure there is just something small wrong here.
Could you please point out where I am going wrong.
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { alert(data); },
error: function (errMsg) {
alert(errMsg);
}
});
I slightly modified you JQuery and it is working as expected now -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
var rolesArray = jQuery.makeArray(roles);
var model = new Object();
model.userId = 1;
model.rolesList = rolesArray;
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(model),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
Output -