I am using Ajax.BeginForm() and a UpdateTargetId. However when the user has successfully completed the form and I have done the processing I want to redirect them to a brand new page.
Calling RedirectToAction() and returning a view from there does not work as it targets the id.
I also need to pass parameters to the action. So is my only option to make a JavaScript call of:
return JavaScript("window.location = 'http://www.somewhere.com/blah/blah?aMyParam=123'");
Is there a more elegant way to do this?
Although the way you are doing is correct but more elegant way to do this is shown below :-
Controller -
[HttpPost]
public ActionResult MyAction(MyModel model)
{
if (model.SomeCondition)
{
// return to the client the url to redirect to
return Json(new { url = Url.Action("MyAction2") });
}
else
{
return PartialView("_MyPartialView");
}
}
View -
#using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { OnSuccess = "onSuccess", UpdateTargetId = "foo" }))
{
...
}
Javascript -
var onSuccess = function(result) {
if (result.url) {
window.location.href = result.url;
}
}
As shown above you can return Json(having url) from controller action and then redirect from onSuccess javascript function.
Related
so have an Ajax.BeginForm that call a PartialView
and return a view (which I'm using it for filtering the products)
but I want to change the main view Model too
I mean after the Ajax.BeginForm got completed
i want to make ViewBag in the PartiaView action
and after that when Ajax.BeginForm got completed
then call a function in cshtml to update the main view model
with that ViewBag
how can I do that
at the end this is my goal:
#functions{
public void ChangeModel(){
Model.Prod = ViewBag.Prod //forget about the casting !
}
}
#using (Ajax.BeginForm("GetStations", "Trains", new { area = "Site" }, new AjaxOptions
{
OnSuccess = ChangeModel(),
}, null))
OnSuccess is a JavaScript callback function,
the C# code will be
#using (Ajax.BeginForm("GetStations", "Trains", new { area = "Site" }, new AjaxOptions
{
OnSuccess = 'mySuccessCallback',
}, null))
Your controller will return something like this
return Json(new { Prod = ViewBag.Prod, ... }, JsonRequestBehavior.AllowGet);
the JavaScript will be
function mySuccessCallback(data, status, xhr) {
var newProdValue = data.Prod; // passed as model from backend
// ... display the new value anywhere with JS or jQuery
}
I am new in MVC .net. I am not able to call view from controller. I have debug the flow. It goes to view successfully but doesn't show view on screen.
Controller name: Downloads
Action name: MakePayment
Redirect view: Success //success is view of View/Downloads/Success.cshtml
Code: DownloadsController
[HttpPost]
public ActionResult MakePayment(Downloads CCM)
{
if (true)
{
return View("Success");
}
else
{
return View("Failure");
}
}
View
#{
ViewBag.Title = "Success";
}
<h2>Your transaction has been completed successfully.</h2>
Method that I use to call the ActionResult MakePayment. I had use Ajax here because I wanted to call javascript function before form get submit.
View: Index.cshtml
#using (Ajax.BeginForm("MakePayment", "Downloads", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnBegin = "payByCreditCard" }))
{
//submit button
}
According to the return View("Success");, it should call the view. In fact when I debug the flow, it goes to Success view but doesn't display the view on screen. It keeps old view on screen.
Degug route after success: _ViewStart-->Success.cshtml-->_Layout.cshtml.
Can anybody suggest me if I am missing something?
Since you are making an ajax call using Ajax.BeginForm helper method, you need to specify where the response (of the ajax call) to be replaced in the DOM. You can specify that using the UpdateTargetId property
#using (Ajax.BeginForm("MakePayment", "Downloads", new AjaxOptions { HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId="YourDivToShowResult"
OnBegin = "payByCreditCard" }))
{
<div id="YourDivToShowResult"></div>
<input type="submit" />
}
Since this is an ajax call, It will not do a redirect. Instead,it will update the content of the div (with Id YourDivToShowResult) in the same page with response coming back which is the markup returned by Success view.
Also since we are showing a partial page update, you might consider returning a partial view.
[HttpPost]
public ActionResult MakePayment(Downloads CCM)
{
if (everything is good)
{
return PartialView("Success");
}
else
{
return PartialView("Failure");
}
}
This will return the markup from either of those views without the layout.
If you want to go to other view you have to redirect the page like:
return RedirectToAction("Success", "Downloads");
I am getting value in a dropdown list and I wanted to get the selected value in controller when user select any value from the dropdown list. My view is -
#using (Html.BeginForm("ApReport", "Sales", FormMethod.Post))
{
#Html.DropDownList("Ddl", null, "All", new { #class = "control-label"})
#Html.Hidden("rddl")
}
controller -
[HttpPost]
public ActionResult ApReport(ApReport Ddl)
{
string Ddlvalue = string.Empty;
if (Request.Form["rddl"] != null)
{
Ddlvalue = Request.Form["rddl"].ToString();
}
}
but I am not getting any value. Also, I donot want to use any submit button.
Thanks in advance
The use of Ajax allows you as the developer to update the main view without reloading the entire page, as well as send data to the server in the background.
This is how I would have accomplished this task.
Firstly, I would have created an action in my controller which returns a JsonResult. This will return a JSON object to your calling jquery code, that you can use to get values back into your views. Here is an example of the action method.
[HttpGet]
public JsonResult YourActionName(string selectedValue) //Assuming key in your dropdown is string
{
var result = DoYourCalculation(selectedValue);
return Json(new { myResult = result }, JsonRequestBehavior.AllowGet);
}
Now, you need to add your jquery code. I would recommend you place this in a seperate javascript file referenced by your view.
Here is the JQuery code, with the ajax call to the Action in your controller. The Ajax call to the server is initiated by the 'change' event of your DropDown, handled in JQuery, as can be seen below.
$(function () {
$(document)
.on('change', '#Ddl', function(){
var valueofDropDown = $(this).val();
var url = '/YourControllerName/YourActionName';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult ;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};
I have tried a number of ways yet had no luck...I must be way off here.
Here is my action link:
#Ajax.ActionLink("Delete all", "Empty",
new AjaxOptions()
{
HttpMethod = "POST",
OnBegin = String.Format("if(!confirm('Are you sure you want to permanently delete {0} items?')){{return false;}}",ViewBag.TotalItems),
OnComplete = "location.reload()",
}
and my ActionResult, I have tried all commented out returns:
public ActionResult Empty()
{
//return Json(new
//{
// redirectUrl = Url.Action("Index", "Home"),
// isRedirect = true
//});
//return RedirectToRoute(new { controller = "Home", action = "Index" });
//return Redirect("http://google.ca");
return RedirectToAction("Index", "Home");
//return new JsonResult() { Data = new { redirectURL = "/" } };
}
Yet I can never get it to redirect to any new page :/
Any help or direction is appreciated...
EDIT: I should note that I didn't originally use the "OnComplete" line until recently after trying everything.
One crude way of doing accomplishing what you need is this:
in the Empty function, replace RedirectToAction to:
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Home");
return Json(new { Url = redirectUrl });
In your javascript, replace
OnComplete = "location.reload()", <-- this additional comma should be removed
to
OnSuccess= "OnAjaxSuccess"
then add a function in Javascript
function OnAjaxSuccess(data) {
window.location.href = data.Url;
}
You get the response, but you didn't get it as you expected.
You make an async call to server and your response is in result parameter of OnSuccess function.
#Ajax.ActionLink("Delete all", "Empty",
new AjaxOptions()
{
HttpMethod = "POST",
OnBegin = String.Format("if(!confirm('Are you sure you want to permanently delete {0} items?')){{return false;}}",ViewBag.TotalItems),
OnComplete = "location.reload()",
OnSuccess = "Success"
}
And you result is here, in data parameter
<script>
function Success(data) {
console.log(data)
}
</script>
data parameter contains page returned by Index action
You can try to use HtmlHelper instead of AjaxHelper
The idee is to post form data from a normal external Html page to another MVC site controller. Then the data is processed almost like using a webservice.
$(document).ready(function () {
var options = {
target: '#output',
success: function(data){ alert('test success'); },
url: http://localhost:57232/Services/SendFormData,
dataType: json
};
$('form').ajaxForm(options);
});
The ActionResult receives the data correctly in the FormCollection object.
[HttpPost]
public ActionResult SendFormData(FormCollection collection)
{
string s = string.Empty;
return Json(new { Success = true, Message = "Message!" }, JsonRequestBehavior.AllowGet);
}
At this point the success result is returned but when it gets to the external form my browser which is in this case IE tries to save or open the bytes returned instead of calling the success callback function.
Because this page is an external page, and not part of the MVC site I cannot use a View or Partial View. What should the return type be?
You need to return partialview result :
[HttpPost]
public ActionResult Form(Comment feedback)
{
if (feedback != null)
{
feedback.CommentedOn = DateTime.Now;
feedback.CommentId += 1;
if (ModelState.IsValid)
{
BlogPost blogpost = db.BlogPosts.Find(feedback.BlogId);
if (blogpost != null)
blogpost.NoofComments += 1;
db.Entry(blogpost).State = EntityState.Modified;
db.Entry(feedback).State = EntityState.Modified;
db.Comments.Add(feedback);
db.SaveChanges();
return PartialView("CommentSuccess", feedback);
}
}
return PartialView("Comment", feedback);
}
Also in the AjaxForm you need to set the UpdateTargetID:
#using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainerdiv" , OnSuccess = "$.validator.unobtrusive.parse('form');", OnComplete = "OnComplete();" }))
in the targetId of the Ajax Form you need to mention the div id where you have to display the response data.
<div id="FormContainerdiv">.</div>
#Html.Partial("Comment", item);
</div>