exclude button from validation - asp.net-mvc-3

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 ...
}
}

Related

Laravel: Two form with one submit button

I want to submit two form into two url and want to submit from two another functions of a Controller.
<form method="post" url="{ '/url1' }">
</form>
<form method="post" url="{ '/url2' }">
</form>
<button type="submit">Submit</button>
Is it possible to do without AJAX??
Simple answer : no, without ajax you can't send two requests.
Complicated answer: unless the first one carries the data for both then in the first response, it sends the second request with the data for it. Which is so complicating things, you should just do it in one request.
You can use jQuery to submit both forms like in the example below:
First of all, add an id to your button like this
<button type="submit" id="submitBtn">Submit</button>
Add ID to your forms:
form method="post" id="form1" url="{ '/url1' }">
form method="post" id="form2" url="{ '/url2' }">
I don't know what is wrong with the stakoverflow editor, that is why i deleted the "<" sign.
3. Now handle the jQuery click event:
$(document).ready(function(){
$('#submitBtn').on('click',function(){
$('#form1').submit();
$('#form2').submit();
});
});
You could give the forms different ids but same action.
Then in the controller called by the submit button, let IF statements check for the form ids and return the respective view desired eg
$requests = $request->all();
$form_Id = $requests['form1_Id'];
if($form_Id != 'id_of_first_form') {
return view('url2');
}else{
return view('url1');
}
If you have a main page form and a modal form and you wanna submit both in order, you can do it with javascript like this
// cause double submits at once
function doubleSubmit()
{
$.post($('#recordPaymentForm').attr("action"), $('#recordPaymentForm').serialize(), function(response) {
$('#submitEditOrderButton').trigger('click');
});
return false;
}
Leave your main page form as it is and change your modal form on submit attribute like this
<form id="recordPaymentForm" method="POST" action="/orders/{{$order->id}}/payments" onsubmit="return doubleSubmit(event)">
Please not that we first submit modal form and then we trigger on click event of submit button (submitEditOrderButton) on the main page. In this example, we first submit payment form and then we trigger click event of main page form which cause a form submit on the main page.

How to undo preventdefault in save event in Kendo Grid

I have a Kendo Grid and set row save event as onAthleteGridSave. I want to add a custom window to set something similar to confirm box. Here is code
function onAthleteGridSave(e)
{
e.preventDefault();
$("#AssignSport").data("kendoWindow").open();
$("#AssignSport").find(".assignsportandsave,.notassignsportandsave")
.click(function () {
if ($(this).hasClass("assignsportandsave")) {
e.model.AssignSportId = $('#AssignEventId').data('kendoDropDownList').value();
}
else if ($(this).hasClass("notassignsportandsave")) {
e.model.AssignSportId = "";
}
$("#AssignSport").data("kendoWindow").close();
})
}
<% Html.Kendo().Window()
.Name("AssignSport")
.Content(() =>
{ %>
...
<input type="submit" class="assignsportandsave" value="Assign Sport And Save" />
<input type="submit" class="notassignsportandsave" value="Not Assign Sport And Save" />
<input type="submit" value="Cancel" onclick="$('#AssignSport').data('kendoWindow').close();" />
...
<%})
The problem is after clicking button in $("#AssignSport").data("kendoWindow"), the program can not go to controller action for Grid which is due to e.preventDefault().
But if removing e.preventDefault(), then program will not wait after $("#AssignSport").data("kendoWindow").open() and immediately go to controller action.
So I want to know if there is a way to undo e.preventDefault() or how to make program wait at where kendo window is opened for button information. Thanks.
You can't undo it, but you can save manually after making your changes to the model by calling saveChanges(). So something like this inside your click handler should work:
e.sender.saveChanges();
$("#AssignSport").data("kendoWindow").close();

MVC3 C# Disabling the Validation Messages on Cancel

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"

After button disabled its value did not posted to controller

I have an controller which has check like that
if (form["submit"].ToString() == "Continue")
{
}
and i have button which is doing submit
<button name="submit" value="Continue">Continue</button>
It was all working well until i decided to disable Continue button on submit to prevent double click using this function:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
So now i don't get value form["submit"] posted on controller.
Any thoughts how may i fix that?
I want still prevent second click but be able to get form["submit"] value posted on controller.
Can you control the submit value in a hidden field in the form? I can't tell what other logic you might need, but when the form renders, you could set the hidden field's value to the submit button's value and change it when necessary using the first script below. As long as it has a name attribute and is enabled (which you'd rarely disable a hidden field) then it will post when the form is submitted.
$(function() {
// this assumes your button has id="myButton" attribute
$(':hidden[name="submit"]').val($('#myButton').val());
});
And of course in your form, you would need a hidden field with name="submit"
<input type="hidden" name="submit" value="Continue" />
Then, whenever the state of your form changes, modify the disabled state of the button and the value of the hidden field to reflect the value (if it changed at all).
There are also frameworks you may find useful for UI features like this. KnockoutJS comes to mind. It can be used to "value" bind input elements. It's probably overkill for this small example, but it could be useful if your UI expands. I've added markup, script and comments below if you're interested.
$(function () {
var viewModel = {
submitValue: ko.observable("Continue")
};
ko.applyBindings(viewModel);
$('form').submit(function() {
if($(this).valid()) {
// the following line will change the both the hidden field's value
// as well as the button's value attribute
viewModel.submitValue("some other value");
// I couldn't follow your selector here, but please note I changed
// the name of the submit button in the markup below.
$(':submit, this).attr('disabled', 'disabled');
}
});
});
KnockoutJS requires you use the data-bind attribute to setup your elements. In your case, you'd bind one property to multiple elements like this:
<button name="submitButton" data-bind="value: submitValue"/>Continue</button>
<!-- and bind the same value similarly in the hidden field-->
<input type="hidden" name="submit" data-bind="value: submitValue"/>

Redirection in controller in MVC 3 with Razor

I need a little help. I'm trying to make a little project in MVC 3 with Razor. A page with 2 buttons: Button 1 and Button 2. When I click on Button 1 I want to go at Page 1. The same with Button 2 ( to Page 2). It's not difficult, BUT I want the redirection to be made in Controller, not in View (cshtml). I know that I need to use ActionName and RedirectToAction, but I don't know how. Please help me!
What you'll need to do is check which button was pressed in the HttpPost part of the controllers action then redirect accordingly.
As a very basic example you could add two
<input type="submit" name="submit" value="<val>">
controls into your forms view each having the same name and a different value (instead of ) then add a string parameter called submit to the HttpPost action. Assuming the buttons have values "button1" and "button2" Then in your action's code you could use:
if(submit == "button1") {
RedirectToAction("Page1");
} else {
RedirectToAction("Page2");
}
to redirect based on which button was pressed
This is a simplified example, but I think you will get my meaning. You simply need to name your buttons and check the formcollection to see which exists in the collection thus indicating which what clicked. see code below:
#using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
<input type="submit" value="Go 1" name="go-1" />
<input type="submit" value="Go 2" name="go-2" />
}
and now the Action implementation.
[HttpPost]
public ActionResult Test(FormCollection collection)
{
if (collection.AllKeys.Contains("go-1")) return View("Page1");
if (collection.AllKeys.Contains("go-2")) return View("Page2");
return View("Index");
}
and thats it.
In your controller action for page 1, you can use RedirectToAction:
public ActionResult Process()
{
// do processing
// redirect to page 2
return this.RedirectToAction("Index", "Page2");
}
You can invoke the Process action from the Page 1 button using either a GET or POST request, depending on if the Process action is idempotent. E.g your page 1 view:
#Html.BeginForm("Process", "Page1", FormMethod.Post)
{
<input type="submit" name="button" value="Submit" />
}
Alternatively, you could use an ActionLink:
#Html.ActionLink("Redirect to Page 2", "Process", "Page1")

Resources