In controller's action is redirected to another action of the same controller. Result: "HTTP Error 404.0 - Not Found". GetData is called via ajax-request in JQuery. On redirect is requested url http://localhost:61327/Home/Index/qwertyQWERTY%20HTTP/1.1. Request address http://localhost:61327/Home/Index/qwertyQWERTY works fine. Code of controller, ajax-request and RouteConfig.cs is shown below.
Routes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{d}",
defaults: new { controller = "Home", action = "Index", d = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default1",
url: "{controller}/{action}/{data}",
defaults: new { controller = "Home", action = "GetData", data = UrlParameter.Optional }
);
}
HomeController
public ActionResult Index(string d)
{
Repository repository = new Repository();
ViewBag.ViewbagValues = repository.GetAllCustomersAndOrders();
Response.Write("Ku-ku");
Response.Write(d);
return View(repository.GetAllCustomersAndOrders());
}
[HttpPost]
[ValidateInput(false)]
public ActionResult GetData(string data)
{
Response.Write(Request.InputStream);
Response.Write("qwerty");
return RedirectToAction("Index", "Home", new {d="qwertyQWERTY"});
}
Script
function SendDataToController(data) {
$.ajax({
url: "Home/GetData",
type: "POST",
datatype: "text",
contentType: "application/text; charset=utf-8",
data: data,
success: function (result) {
alert("Data was send to the controller");
window.location = result.URL;
},
error: function (err) {
alert("Error: data was not send to the controller");
}
});
alert(data);
In addition to Stephen Muecke's note - this will work with your javascript:
[HttpPost]
[ValidateInput(false)]
public ActionResult GetData(string data)
{
var data = new { URL = Url.Action("Index", "Home", new {d="qwertyQWERTY"}) };
return Json(data, JsonRequestBehavior.AllowGet);
}
Related
So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}
you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"
I created a Web API in DNN with sample provided in
http://www.dnnsoftware.com/community-blog/cid/142400/getting-started-with-services-framework-webapi-edition
with this example i modified HelloWorld method for getting parameter, but not able to get parameter in action while passing through ajax . here is my code
public class RouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute(
moduleFolderName: "MyServices",
routeName: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
namespaces: new[] { "MyServices" }
);
}
}
public class WelcomeController : DnnApiController
{
[AllowAnonymous]
[HttpGet]
public string HelloWorld(WelcomeParameter id)
{
return "test" + id.UserID + id.ClientID + id.LanguageID;
}
}
public class WelcomeParameter
{
public int UserID;
public int ClientID;
public int LanguageID;
}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: "GET",
url: "desktopmodules/myservices/apI/Welcome/HelloWorld/",
data: JSON.stringify({"id":{ "UserID": 1, "ClientID": 1, "LanguageID": 1}}),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
})
.done(function (msg) {
alert("Content: " + msg);
});
});
</script>
This action is not returning output as
test111
test111
i m getting error as 405 Method Not Allowed "The requested resource
does not support http method 'POST'."
You want to add action method with HTTP POST too.
public class WelcomeController : DnnApiController
{
[AllowAnonymous]
[HttpGet]
public string HelloWorld()
{
return "";
}
[AllowAnonymous]
[HttpPost]
public string HelloWorld(WelcomeParameter id)
{
return "test" + id.UserID + id.ClientID + id.LanguageID;
}
}
Hello by default ASP MVC routes are looks like:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
but is it possible to use it in next way with not optional ID:
routes.MapRoute(
name: "Default",
url: "{id}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index", id = 0 }
);
Yes, it is possible.
Just tried:
RoutesRegistration:
routes.MapRoute(
"Default",
"{id}/{controller}/{action}",
new { controller = "Home", action = "Index", id = 0}
);
Controller:
public class HomeController : Controller
{
public ActionResult Index(int id)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
my url is look like :
localhost:1336/PartPicker/Part/Mobile/list_view
i want ajax post request. But ajax request is not wroking
my controller action code
public JsonResult getProduct(String partid, String id)
{
return Json("success");
}
my ajax request code
function btn_Click()
{
var sdata = { partid: 'abc', id: 'xyz' };
$.ajax({
type: 'POST',
url: 'getProduct',
data: JSON.stringify(sdata),
contentType: 'application/json;charset=utf-8',
dataType: "jsonp",
processdata: false,
success: function (data) { alert(data);},
error: function (serverdata) { alert("eror " + serverdata.responseText) },
async: false
});
}
route settings
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{partid}/{id}/",
defaults: new
{
controller = "PartPicker",
action = "Part",
partid = UrlParameter.Optional,
id = UrlParameter.Optional
},
namespaces: new[] { " abc.Controllers" }
);
I can't identify why ajax request is not working. Please someone help me
Try this:
var sdata = "{'partid':'abc','id':'xyz'}";
Here is my view
<div>
#using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
{
#Html.TextBoxFor(x=> x.Name)<br />
#Html.TextBoxFor(x => x.LastName)<br />
#Html.TextBoxFor(x => x.Age)
<input type=submit value="submit" />
}
</div>
<script>
$(document).ready(function () {
$('#FormPost').submit(function (e) {
//This line will prevent the form from submitting
e.preventDefault();
alert('ajax post here');
$.ajax({
type: 'POST',
url: $('FormPost').attr('action'),
data: $('FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.statusText);
},
success: function (response) {
alert('resp: ' + response.data);
}
});
});
});
</script>
These are the Home controller's methods:
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
return Json("name posted was: " + _vm.Name);
}
This is the route map
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When the page loads it goes to the Index action method, which is understandable. However, when I submit the form it is going to the Index action method again. Why is that?
The alert message 'ajax post here' gets shown followed by the success alert ('resp: ' + response.data). However since I am not returning anything in the Index I get a resp: undefined in the alert box.
How do I fix this so that the form post goes to the public JsonResult jQueryPost(IndexVM vm) method? I also tried replacing the JsonResult to ActionResult and it fared the same.
You forgot the # in you jQuery selectors:
$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.statusText);
},
success: function (response) {
alert('resp: ' + response.data);
}
});