MVC3 C# Disabling the Validation Messages on Cancel - asp.net-mvc-3

I have an MVC2 C# .Net Web App. We are using the built in MVC3 Validation using the Domain class properties [Required(ErrorMessage = "Start From is required.")] and in the HTML #Html.ValidationMessageFor(model => model.StartFrom)
However, when we submit the page using the Cancel button, the validation is fired stating the "Start From is Required" and therefore not exiting the page. How can I disable the Validation on the Cancel button? Or submit the page without firing the Validation?

I think you need to override the default behaviour of the submit button i.e., Cancel button in your case.
Say you have the cancel button like this:
<input type="submit" id="btnCancel" value="cancel"/>
now write the jQuery to override the default behaviour
$(function(){
$('#btnCancel').click(function(e){
e.preventDefault();
//or you can return false from this method.
//return false;
});
});

I found an answer here, on Stackoverflow :) jQuery disable validation
Each of the first two answers in that link worked for me. #Karthik, thanks for the answer. It got me on the right track
Answer 1:
<input id = "theCancel" class="cancel" type="submit" value="Cancel" />
Answer 2:
$(function () {
$('#theCancel').click(function (e) {
$("form").validate().cancelSubmit = true;
});
});
I chose answer 2 and put it in our global js file. All of our Cancel buttons have an id of "theCancel"

Related

How to reference the submit button in a jqGrid modal form

How do I reference the submit button? I am trying to set the focus on the submit button when a certain field is exited.
Here's an example of my approach:
dataEvents:[{
type:'blur',
fn: function(){
$('#add').focus();
}
}]
Have also tried $('#submit').focus();
Note: This button is the Add button of the Add New Record modal form of jqGrid
Any help appreciated.
You should be able to set the focus after the blur via a
$('#sData').focus();
Add id in submit button and try this
$(document).ready(function(){
$("#submit").focus();
});
<input type="submit" value="u" name="submit" id="submit"/>

ASP.NET MVC - Having a confirmation button with a Form

I have an strongly typed view for my model and what I'd like is that when the user clicks on submit, a confirmation box pop up confirming that the user does indeed wish to submit the form, if they click cancel then it shouldn't fire the HttpPost Action for that View, is this possible?
Of course it is possible. I like to use an unobtrusive approach. Here is a simplified example:
jQuery(document).ready(function () {
jQuery('[data-confirm]').click(function (e) {
if (!confirm(jQuery(this).attr("data-confirm")))
{
e.preventDefault();
}
});
});
Then you only need to add a data-confirm attribute to your submit button for example
<input type="submit" data-confirm="are u sure?" />
Of course you can use this attribute on links, buttons, etc. you are not restricted to submit buttons only, and if you want to implement a fancier confirm dialog later than you will have to replace the code only in one place.
function doSubmit()
{
if(window.confirm("ARE YOU SURE TO PERFORM THIS ACTION"))
{
return true;
}
else return false;
}
call doSubmit() function on onsubmit event of the form,
Eg- onsubmit="return doSubmit()
you can add a simply jQuery call for that.
at the end of your view add:
<script type="text/javascript">
$("form").submit(function() {
return confirm('Are you sure?');
});
</script>
or, add a
onsubmit="return confirm('Are you sure?');"
as a new element property
I believe this can be done by overriding the submit button using jquery. Jquery .submit()
This way, when the person hits submit you can show a message and either submit it or cancel it.

exclude button from validation

I have a form with validators and 2 buttons inside form:
<input type="submit" class="LFL_btn" value="" />
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn" id="btnRegister" />
but validator works and for second button too. Why and how to fix it?
Why?
Because jquery.validate kicks in when you submit a form by hijacking the submit event of this form. And since both are submit buttons, validation is run for both of them.
how to fix it?
Add class="cancel" to the button you want to exclude from validation which will instruct the jQuery.validate plugin not to run validation:
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" />
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" />
This has been covered in the documentation.
Obviously all this refers only to client side validation. On the server it's a whole different story. If you wanted to disable validation when some button is clicked you will first need to know which button was clicked. This could happen by giving the first button a name attribute and then inspecting on the server the value of this parameter from the request:
<button type="submit" class="LFL_btn" name="validate" value="validate">Validate</button>
and then inside your controller action check if this button was used to submit the form and apply validation only in this case:
[HttpPost]
public ActionResult Foo(string validate)
{
if (!string.IsNullOrEmpty(validate))
{
// the Validate button was clicked:
var model = new MyViewModel();
if (!TryUpdateModel(model))
{
// there were validation errors => redisplay the view
return View(model);
}
// validation went fine => do some processing...
}
else
{
// the image button was clicked
// do some other processing ...
}
}

Why is a form's submit event not firing (jQuery)?

I have a form + layout like so:
<form ...>
<div id="editor">
[form html]
<input type="submit" value="Submit form" />
</div>
</form>
And the following javascript:
$(function() {
var form = $('#editor').parents('form');
alert(form.length); // this alerts "1"
$(document).on('submit', 'form', function() {
alert('document form submit fired'); // this works as expected (alerts)
});
form.on('submit', function() {
alert('selected form submit fired'); // this is never alerted
});
});
This form is not loaded via ajax. When the page loads, the first dialog alerts "1". However when submitting the form, only one alert is fired -- the one that triggers submit for all forms in the document.
Why would this happen?
It does work. Something else is happening which is preventing the second alert from firing.
Your form selector is incorrect.
Try and do this
$("form").on('submit', function() {
Pretty sure this should work
Actually if nothing is being loaded through ajax or dynamically through javascript
You can just do
$("form").submit(function() {
EDIT
Scratch my above. Didn't see you set the value of form. Check out http://jsfiddle.net/s3fvM/1/. Seems to be working fine to me. both are firing and alerting.

multiple button click in asp.net MVC 3

I am having multiple dynamic buttons on my asp.net mvc 3 page. what is the best way to handle button click in asp.net mvc 3? there is no event handling in asp.net, so what is the best practice to hadle.?
You could handle the buttons clicks using javascript by subscribing to their click event. For example with jQuery you could give those buttons a class and then:
$(function() {
$('.someClass').click(function() {
// a button was clicked, this will point to the actual button
});
});
or if those are submit buttons of a form you could give them the same name and different values and then on the server test the value of the name parameter. It's value will equal to the button that was clicked.
Let's suppose for example that you have the following form with multiple submit buttons:
#using (Html.BeginForm())
{
... some input fields
<button type="submit" name="Button" value="delete">Delete data</button>
<button type="submit" name="Button" value="save">Save data</button>
}
Now inside the controller action you are posting to you could determine which button was clicked:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
var button = Request["button"];
if (button == "save")
{
// the save button was clicked
}
else if (button == "delete")
{
// the delete button was clicked
}
...
}
If the buttons do not require the same form data, then you can create two forms with different action methods. This is the easiest solution.
If you need to use the same form data, then there are a number of methods, inclduing Darin and tvanfosson's approaches. There is also an approach based on attributes that will select the correct action method based on which button is clicked.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
Depends on what the buttons are doing. If they are logically separate actions, then you could have each postback to a separate action on the server side. This often also works they are variants of the same action, Save vs. Cancel, for instance where Save posts back the form and Cancel redirects to you the previous url (say, going back to details from edit). If the buttons represent different data that would get posted back to the same action, you can give them different values. If the buttons are named, the values will get posted back along with the rest of the form, assuming they are included in the form. If posting back from AJAX, you might need to explicitly serialize the button value along with the form.
Example of Save/Cancel
#using (Html.BeginForm())
{
//...
<button type="submit" class="submit-button button">Save</button>
#Html.ActionLink( "Cancel", "details", new { ID = Model.ID }, new { #class = "cancel-button button" } )
}
Then use CSS, perhaps in conjunction with jQuery UI to style the buttons.
<script type="text/javascript">
$(function() {
$('.button').button();
...
});
</script>

Resources