ASP.Net MVC 3.0 Ajax.BeginForm is redirecting to a Page? - asp.net-mvc-3

In ASP.Net MVC 3.0 i am using a Ajax.Beginform
and hitting a JsonResult
on success of the form i am calling a jQuery Function.
but for some reason my form is redirecting to JsonAction
my View
#using (Ajax.BeginForm("ActionName", "Controller", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ShowResult"
}, new { id = "myform" }))
{
// All form Fields
<input type="submit" value="Continue" class="button standard" />
}
My controller
public JsonResult ActionName(FormCollection collection)
{
return Json(new { _status },JsonRequestBehavior.AllowGet);
}
jQuery
<script type="text/javascript">
function ShowResult(data) {
// alert("I am at ShowResult");
if (data.isRedirect) {
window.location.href = json.redirectUrl;
}
}
for some reason, when i click submit.
it runs the JSonResult and redirects the page to host/controller/actionname
I have included my
<script src="#Url.Content("jquery.unobtrusive-ajax.min.js")"></script>
in my layout.cshtml
can any one tell me what could be wrong?
I found the problem. Now i have to find the solution
on submit
I am validating my form
$("#myform").validate({
submitHandler: function (form) {
// my logic goes here....
}});
If i exclude the validation Ajax form works as expected.
But if i validate my form then ajax form is not working as expected
Thanks

when this happens its almost always because your script files aren't loaded
note from:
http://completedevelopment.blogspot.com/2011/02/unobstrusive-javascript-in-mvc-3-helps.html
Set the mentioned flag in the web.config:
Include a reference to the jQuery library ~/Scripts/jquery-1.4.4.js
Include a reference to the library that hooks this magic at ~/Scripts/jquery.unobtrusive-ajax.js
So load up fiddler http://fiddler2.com and see if the scripts are being called and loaded.

Related

Validate only ajax loaded partial view

I have a form with some controls. There is a button on the form which loads a partial view. Inside the partial view, there are two required field textboxes along with a button. And when its clicked, I need to display error messages only for textboxes which are inside the partial view, but not for the fields in the actual form. And when I click form's submit button, all error messages must show up.
After partial view is loaded, I am re-initializing the validation plugin as below.
$('#test').removeData("validator");
$.validator.unobtrusive.parse('#test');
I tried using validation attribute described in below thread but its not working. Maybe it works for normally loaded views.
ASP.NET MVC Validation Groups?
However, I can validate individually by calling textbox1.valid() and textbox2.valid(). But I think I am missing standard way of doing it. Any help is appreciated.
you can do this by submitting your partial view using Ajax.BeginForm()
//In Partail View
#model SomeModel
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId"}))
{
#Html.EditorFor(mode=>model.FirstText)
#Html.EditorFor(mode=>model.SecText)
<input type="submit" value="save">
}
//In Controller
public ActionResult SomeAction(SomeModel model)
{
return PartaiulView(model);
}
here you can validate your Partial View
NOTE: when you submit you form using Ajax.BeginForm you must specify "UpdateTargetId" where your result will be appear on View.
//In View
<div id="targetId">
#Html.Partail("PartialView")
</div>
OR if you want to Redirect to another action if your model is valid then modified your action
public ActionResult SomeAction(SomeModel model)
{
if(ModelState.IsValid)
{
return Json(new {redirect = #Url.Action("SomeAction","SomeController")})
}
return PartaiulView(model);
}
then in partail view you can invoke OnSuccess method of Ajax.BeginForm
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId",OnSuccess="success"}))
{
}
<script type="text/javascript">
function success(data)
{
if(data.redirect)
{
windows.location = data;
}
}
</script>
check both way which one is suitable to you.

MVC3 Razor Ajax.ActionLink won't use POST method

I've got a page that contains multiple links. These links should do an ajax post and callback. However, the link is doing a Get instead of a Post. This causes a 404 error since I do not have an action method to handle a get at the requested URL.
If I remove the HTTPPost attribute from my Action method, the link works, but the call back fails and the Json I return is rendered in a new page.
Here is the code I'm using in my view.
<td id="action-#item.ItemID">#Ajax.ActionLink("Add", "AddToOrder", new { itemID = item.ItemID }, new AjaxOptions { HttpMethod = "POST", OnSuccess = "actionCompleted" }, new { id = "add-" + item.ItemID })</td>
This ends up adding this HTML:
<td id="action-012679"><a data-ajax="true" data-ajax-method="POST" data-ajax-success="actionCompleted" href="/mysite/neworder/AddToOrder?itemID=012679" id="add-012679">Add to Order</a></td>
My Controller has the following Action Method.
[HttpPost]
public JsonResult AddToOrder(string itemID) {
return Json(new { id = itemID, Action = "Added", "Just getting this working"});
}
My callback method that is called on Success looks like this:
<script language="javascript" type="text/javascript">
function actionCompleted(response, status, data) {
alert("We have returned");
}
</script>
If I change the [HTTPPost] attribute on my action method to [HTTPGet] I get an Json error. I can fix this by adding the JsonRequestBehavior.AllowGet to my return value, but this doesn't use the call back function defined on the page and fails.
Any help would be appreciated.
Probably you don't have jquery.unobtrusive-ajax.js script attached to page and link is gracefully degraded to regular anchor.
In order to have this working properly. You need to add references to these scripts on your page:
MicrosoftAjax.js
MicrosoftMvcAjax.js

Avoiding Duplicate form submission in Asp.net MVC by clicking submit twice

I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :-
[HttpPost]
public ActionResult Create(BrandPicView brandPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(brandPic.Picture.PictureUrl))
{
Picture picture = new Picture();
picture.PictureUrl = brandPic.Picture.PictureUrl;
db.Pictures.Add(picture);
brandPic.Brand.PictureId = picture.Id;
}
db.Brands.Add(brandPic.Brand);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
But, while testing, I saw that if the form is clicked again and again, the multiple entries are submitted and saved into the database.
How can i make sure that if the form has been submitted once to the server, then no duplicates are submitted.
I don't think this is quite a duplicate of the answer referenced in the comment, since the link is for spring MVC, and this question is for .NET MVC.
I actually spent a few hours on this a while back, and came up with the following. This javascript hooks nicely with the unobtrusive jquery validation, and you can apply it to any form that has <input type="submit". Note that it uses jquery 1.7's on function:
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});
$(document).on('submit', 'form', function () {
var button = $(this).find(':submit');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
The setTimeouts are needed. Otherwise, you could end up with a button that is disabled after clicked even when client-side validation fails. We have this in a global javascript file so that it is automatically applied to all of our forms.
Update 16 Nov 2020 by #seagull :
Replaced selector input[type="submit"] with :submit so it will work with <button type="submit" /> as well
The solution for mvc applications with mvc client side validation should be:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
Disable the button on Submit clicked. This can be done using JQuery/Java Script.
Look at this example on how to do this.
You can use this one. It includes unobtrusive jQuery validation.
$(document).on('submit', 'form', function () {
var buttons = $(this).find('[type="submit"]');
if ($(this).valid()) {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', true);
});
} else {
buttons.each(function (btn) {
$(buttons[btn]).prop('disabled', false);
});
} });
For jQuery validation please incllude
~/Scripts/jquery.validate.min.js
~/Scripts/jquery.validate.unobtrusive.min.js
You can use ajax.BeginForm insted of html.BeginForm to achieve this, if you use OnSuccess insted of OnBegin you can be sure that your method execute successful and after that your button turn to deactivate,with ajax you stay
in current view and you can update your current view instead of redirection
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dive",
OnBegin="deactive"
}))
{
//body of your form same as Html.BeginForm
<input type="submit" id="Submit" value="Submit" />
}
and use this jquery in your form:
<script type="text/javascript" language="javascript"> function deactive() { $("#Submit").attr("disabled", true); }</script>
be careful for using ajax you have to call this scrip in the end of your page
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Disabling the button is fine via JavaScript but what if the user has it disabled or they bypass it? If you use client side security then back it up with server side. I would use the PRG pattern here.
window.onload = function () {
$("#formId").submit(function() {// prevent the submit button to be pressed twice
$(this).find('#submitBtnId').attr('disabled', true);
$(this).find('#submitBtnId').text('Sending, please wait');
});
}

How to redirect to Login page from an Ajax postback?

I work on an MVC 3 application. My cshtml page looks like this:
#Ajax.BeginForm("Filter", new AjaxOptions() { UpdateTargetId = "div_GridPlaceholder")
{
...some HTML
<input id="btn_Filter" type='submit' ... />
}
<div id="div_GridPlaceholder">...</div>
The Filter ( ) action method marked with the Authorize attribute returns some string at the moment. Everything works fine but when the forms authentication ticket expires and I hit the btn_Filter button, my Login page gets rendered in the div_GridPlaceholder which is pretty strange. I would like to have the see the Login page rendered on the whole page instead of inside that div.
Any help is appreciated.
In your Logon action you could append a custom response HTTP header:
public ActionResult LogOn()
{
Response.AppendHeader("X-LOGON", "true");
return View();
}
and then subscribe for the complete event and test for the presence of this header and act accordingly:
$(function () {
$('#div_GridPlaceholder').ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
if (XMLHttpRequest.getResponseHeader('X-LOGON') == 'true') {
window.location.href = '#Url.Action("LogOn", "Account")';
}
});
});

"UpdatePanel" in Razor (mvc 3)

Is there something like UpdatePanel (in ASPX) for Razor?
I want to refresh data (e.g. table, chart, ...) automaticly every 30 seconds.
Similar to clicking the following link every 30 seconds:
#Ajax.ActionLink("Refresh", "RefreshItems", new AjaxOptions() {
UpdateTargetId = "ItemList",
HttpMethod = "Post"})
Edit:
I may should add that the action link renders a partial view.
Code in cshtml:
<div id="ItemList">
#Html.Partial("_ItemList", Model)
</div>
Code in Controller:
[HttpPost]
public ActionResult RefreshItems() {
try {
// Fill List/Model
...
// Return Partial
return PartialView("_ItemList", model);
}
catch (Exception ex) {
return RedirectToAction("Index");
}
}
It would be create if the PartielView could refresh itself.
You can try something similar to the following using Jquery (have not tested though)
<script type="text/javascript">
$(document).ready(function() {
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
});
</script>
The above code should be placed in the containing page i.e. not the partial view page. Bear in mind that the a partial view is not a complete html page.
My initial guess is that this script can be placed in the partial and modified as follows. Make sure that the ajax data type is set to html.
<script type="text/javascript">
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
</script>
Another alternative is to store the javascript in a separate js file and use the Jquery getScript function in ajax success callback.
Well, if you don't need the AJAX expierience than use the HTML tag:
<meta http-equiv=”refresh” content=”30; URL=http://www.programmingfacts.com”>
go here: http://www.programmingfacts.com/auto-refresh-page-after-few-seconds-using-javascript/
If someone wants the complete code for a selfupdating partial view have a look!
Code of the Controller:
[HttpPost]
public ActionResult RefreshSelfUpdatingPartial() {
// Setting the Models Content
// ...
return PartialView("_SelfUpdatingPartial", model);
}
Code of the Partial (_SelfUpdatingPartial.cshtml):
#model YourModelClass
<script type="text/javascript">
setInterval(function () {
$.post('#Url.Action("RefreshSelfUpdatingPartial")', function (data) {
$('#SelfUpdatingPartialDiv').html(data);
}
);
}, 20000);
</script>
// Div
<div id="SelfUpdatingPartialDiv">
// Link to Refresh per Click
<p>
#Ajax.ActionLink("Aktualisieren", "RefreshFlatschels", new AjaxOptions() {
UpdateTargetId = "FlatschelList",
HttpMethod = "Post", InsertionMode = InsertionMode.Replace
})
</p>
// Your Code
// ...
</div>
Code to integrate the Partial in the "Main"-View (ViewWithSelfupdatingPartial.cs):
#Html.Partial("_FlatschelOverview", Model)
The <meta refresh ..> tag in HTML will work for you. Its the best option
Traditional controls don't works in ASP MVC
You could do it using Jquery timers http://plugins.jquery.com/project/timers
Other option could be to use the Delay function
In your target is as simple as refresh the whole page, this SO link will be of your interest: Auto refresh in ASP.NET MVC
Hope It Helps.

Resources