This is my View Page:
#using (Html.BeginForm("GetAction", "GetController", FormMethod.Post))
{
//bodypage:
}
This is my controller method.
[ActionName("GetAction")]
[HttpPost]
public ActionResult GetAction(string i)
{
//doing stuff:
return View();
}
This is my Ajax call
$(document).ready(function () {
$("#value").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetAction", "GetController")',
data:
{
'i': $("#i").val()
}
});
});
});
I dont get it why controller getting called twice. I also even config my route class but i
dont know how to do it.
Since you are using ajax remove from the view button
type="submit
and fix the javascript:
$("#value").click(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
....your ajax code
});
Related
I have a method which return an action to a different controller. I am using return RedirectToAction and passing a parameter with it. The parameter successfully passed to the other controller. But it does not return any view. The page should load and return a new view. Here is my code:
Controller 1:
public ActionResult Work(int id, int staffId)
{
return RedirectToAction("CreateStaffWork", "Staff", new { id = staffId});
}
Controller 2 (Staff):
public ActionResult CreateStaffWork(int id)
{
Staff staffInfo= db.Staff.Find(id);
StaffInputModel newStaffWork = new StaffInputModel { StaffId = staffInfo.Id };
return View(newStaffWork);
}
It should return CreateStaffWork view, but the page does not reload. There is no error while running the code. What should I do for the view to return?
I submit the form using ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#LoadStaffListTable tbody").on('click', '.select', function (e) {
e.preventDefault();
$.ajax({
url: '/StaffWork/Work',
type: 'POST',
data: { id: $(this).data('id'), staffId: $(this).data('staffId') },
dataType: 'json',
}); // end ajax
});
});
As mentioned in the comments, the purpose of ajax is to stay in the same page. If you're redirecting to a new page, you simply redirect to the Work action methods with proper parameters.
Change your click event handler to:
$("#LoadStaffListTable tbody").on('click', '.select', function(e) {
location.href = '#Url.Action("Work", "StaffWork")?id=' + $(this).data('id') + '&staffId=' + $(this).data('staffId');
});
I'm using MVC 2 and trying to make an ajax call to the controller method.
Controller:
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
View:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '<%= Url.Action("FirstAjax", "AjaxTest") %>';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
In above code please notice my controller. to get the code working i had to add to methods with HTTPPOST and HTTPGET and even the parameter a is not related i just added it because i can not add two methods with the same signature.
I guess this might not be the correct way to do this. please explain the most suitable approach for this kind of code.
UPDATE:
adding a single method with out POST and GET does not work. It just print the string "chamara" on the page.alert not firing
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
From your explanation I think the code what you need is like :
AjaxTestController.cs
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Script:
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '<%= Url.Action("FirstAjax", "AjaxTest") %>';
$.ajax({
type: "GET",
url: serviceURL,
success: successFunc,
error: errorFunc
});
function successFunc(data) {
alert(data);
}
function errorFunc(xhr, status, err) {
alert('error');
}
});
</script>
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
UPDATE:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
And please refer this link for further reference of how a method becomes an action. Very good reference though.
I´m new with MVC. I´m using MVC4.
I'm having an issue with a callback. If I alert before and after the post() call both alerts show but the call doesn't fire.
[HttpGet]
[Authorize]
public ActionResult Dashboard(int Menu)
{
//some code
return View("Dashboard");
}
<script>
$(document).ready(function () {
$.post("../Client/GetFact", {},
function (data) {
//some code
});
});
</script>
[HttpPost]
[Authorize]
public JsonResult GetFact()
{
//some code to fill object_data
var data = object_data;
return Json(data);
}
As long as I leave ActionResult Dashboard without a parameter is works. If I add a parameter to Dashboard(int Menu) then the call back to GetFact doesn't work.
I searched and found a similar post and follow the instructions given by you guys, but still does not work( looked at: getJSON not working if the mvc model view controller has a parameter).
I do not know what I'm doing wrong. Can you help? Thank's!
I do something similar with $.get, using jquery with the #Url.Action instead of the url.
in addition to using the FormContext to pass to my Action :
Place just before #using (Html.BeginForm())
#{ ViewContext.FormContext = new FormContext(); }
example :
$.get('#Url.Action("ActionName", "ControllerName")', { IDName: $('#IdName').val() }, function (data) {
//Do Something here with the data
});
I would imagine form post would be
$.post('#Url.Ation("ActionName", "ControllerName")', function (data) {
//Do Something here with the data
});
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: data,
success: success,// -> call alert here
dataType: dataType});
I am working on project using MVC 3.0(Razor framework). I am trying to get values from controller to view using Viewdata on Button click in Javascript Method.Its coming on document.ready but not on Button click.So please help to get the viewdata value on button click.
Following is my code
[HttpPost]
public ActionResult Update()
{
ViewData["myInfo"] = "my info";
return View();
}
And my JAvascript code:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
$.post("/ImportCSV/Update", {},
function ()
{
var g = '#ViewData["myInfo"]';
});
});
});
</script>
I want to show Viewdata value on button click
You'd better return a JSON result in this case. ViewData is bad. Don't use it. In your case it doesn't work because you need to define a corresponding view of this controller action that will interpret the ViewData and it is the final HTML fragment that you will get in the AJAX success callback. Using JSON you can directly send some data to the calling script:
[HttpPost]
public ActionResult Update()
{
return Json(new { myInfo = "my info" });
}
and then send an AJAX request to this controller action:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
var url = #Url.Action("Update", "ImportCSV");
$.post(url, {}, function (result) {
var myInfo = result.myInfo;
alert(myInfo);
});
});
});
</script>
Here is my problem:
Inside a jQuery dialog I have the following code:
<%:Ajax.ActionLink("Yes", "SendClaim", "Claim", new { id = Model.ExpenseId }, new AjaxOptions { UpdateTargetId = "dialog" }, new { #class = "button" })%>
When stuff fails in the controller based on roles I return a partial view that replaces the existing dialog (see UpdateTargetId = "dialog").
When everything works I want to do a redirect to another page (an index of all claims) to stop the user performing additional actions but this entire page is rendered inside the jQuery dialog due to it being an ajax request with an update id.
What is the correct way to approach the problem?
I'm a bit of a novice, but I find I have more control with the following approach instead of using Ajax.ActionLink. Hopefully it helps and I have understood what you want to do correctly.
Claim Controller:
[AcceptVerbs(HttpVerbs.Post)]
public Json Send(int expenseId)
{
// Check user stuff
if(valid)
// do stuff
return new Json(true, JsonRequestBehavior.AllowGet);
else
return new Json(false, JsonRequestBehavior.AllowGet);
}
jQuery
function submitClaim() {
$.ajax({
url: "/Claim/Send",
type: "POST",
dataType: "json",
data: { 'expenseId': <%=Model.ExpenseId> },
success: function (data) {
if(data) { // if successful, redirect
document.location = "Claim/Index";
}
else { //load your partial view into your dialog
$("#idOfYourDialog").load('Claim/Error/');
}
},
error: function (xhr) { }
});
}
html
Submit
Returned an 'All OK' dialog and had the following javascript when the user clicks the ok button:
function redirect() {
document.location = "<%:(String)ViewBag.Redirect %>";
}
$(document).ready(function() {
$(".ui-dialog-titlebar-close").click(function() {
redirect();
});
});
Seems unavoidable - you can't seem to do an RedirectToAction when the controller action has been called from Ajax.ActionLink as the response will be stuck into the updatetargetid.