I have the following cshtml:
using (Html.BeginForm(MVC.ProbleemRapport.ActionNames.Form, MVC.ProbleemRapport.Name, FormMethod.Post, new { id = "probleemForm" }))
{
<button type="submit" id="verzendenBtn" class="btn actie" title="#StartSchermResource.BtnSend">#StartSchermResource.BtnSend</button>
}
I have a jquery that does the following :
$('#verzendenBtn').click(function () {
$('#probleemForm').find('.error').remove();
// do some validation
if (value === false) {
return value;
}
});
Now when i click my button, the validation works fine.
But when everything is completed and the post happens to the controller, I get a json-result. Which is normal since my action returns a json result containing "true" of "false".
When the result is "true", I need to hide the form.
When the result is "false", I need to hide the form and display a message that something went wrong.
but the only thing that is happening now, is that I get the request to open the json.
What am I forgetting?
you should be able to do $('#probleemForm').hide(); and if you want to show it again just change hide() to show()
for the message create something like <div id="myMessage"/>
then in $('#myMessage').val("something went wrong") this will keep the form open of course. If you want to close the form you can use a standard #URl.Action and redirect or you could just do a simple Javascript alert('error messsage')
Related
The issue I am facing now is a button click event is automatically being fired when enter key is pressed in Html.TextBoxFor(). I am having a main view. In this view there are 3 buttons. On each of 2 button click a partial view is opened and during 3rd button click, a new view is opened. Please see the code below :
<script>
$(document).ready(function () {
SetUpDatePickers();
});
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
$('#button2').click(function (event) {
$('#divRequestTT').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
});
$('#button3').click(function (event) {
window.location.href = '/UserManagement/UsersList/';
event.preventDefault();
});
</script>
I clicked button1 and the first partial view is opened :
The partial view has below code :
#Html.TextBoxFor(u => u.TrajName, new { #class = "txtboxclass", #id = "TrajName" })
My issue is when I press "Enter" key inside this text box, the code for button1 in main view is being executed :
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
This results in all the buttons being hidden and the view becomes useless unless user reloads the view forcefully.
I tried to handle the onchange() event of the textboxfor and redirected to below function, but it doesn't handle.
function EnterKeyFilter() {
if (window.event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
}
}
Even I tried the same function for div - click() .. It doesn't work.
When I press the enter key the exact button1 click is being handled with this information event = j…y.Event {originalEvent: MouseEvent, type: "click", timeStamp: 7055.025000000001, jQuery110208686809991100928: true, toElement: button#button1.
But I am not clicking it either. The partial view is not part of a form also and form submission is not the issue. I am new to ASP.NET MVC and confused with this strange behavior. Please help. Thanks in advance.
If you want to disable your press enter in your keyboard, try this:
$(function () {
//On your document ready function, add this:
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
return false;
}
});
}
Try to keep all three buttons in different form tags and made them submit button.
So in this case, whenever you hit enter in a form input, respective button will be clicked. To prevent full page postback, use e.preventDefault() in button click event.
HTML:
<form id="frm1">
-------------
-------------
<input id="btnSubmit" type="submit" value="submit" />
</form>
jQuery
$("#btnSubmit").click(function(e){
e.preventDefault();
-- rest of code
});
This is a follow on to similar question but taking suggestions into account.
Render part of page on dropdown selection
I have a chart on my main view which I would like to update partially when a dropdown selects different values.
The page renders correctly the first time, but when I select a new value in the dropdown, then I think the .submit script is failing in the script .submit() because when I put a break on window.submitAjaxForm it is never reached.
_PnlChart.cshtml
<img src="#Url.Action("CreateTraderPnlChart3")" width="600" height="600" align="middle" vspace="50" />
My mainview Index.cshtml:
<div class="w3-half">
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#using (Ajax.BeginForm("GetEnvironment",
new RouteValueDictionary { { "Environment", "" } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }, new { id = "ajaxForm" } ))
{
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"],
new
{ onchange = "submitAjaxForm()" })
}
</script>
<script type="text/javascript">
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
window.submitAjaxForm = function(){
$('form#ajaxForm').submit();
}
</script>
</div>
My controller:
public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
Session["Period"] = dropdownlistReturnValue;
return PartialView("~/Views/Employee/_PnlChart.cshtml");
}
This line in your code,
eval($(this).attr('onsubmit')); return false;
I am not sure what you were intending to do here. But from your question, i assume you wanted to do a form submission. But that line will not submit the form. The expression $(this).attr('onsubmit') is going to return undefined as your form does not have an onsubmit attribute defined.
But you already have the form submit code in your other method (submitAjaxForm). So if you simply remove the $('form#ajaxForm').submit handler (apparently it does not do anything useful), your code will work. When you change the dropdown, it will make an ajax form submission.
But your form action is set to GetEnvironment action method. That means your ajax form submission will be to that action method. In your question you have a different action method which returns the updated chart content. It does not makes sense!
I personally prefer to write handwritten ajax calls instead of relying on the ajax action helper methods. The below is the code i would probably use (Except the dropdownlist code. read further)
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"], new
{ data_charturl = Url.Action("PeriodSelection","Home")})
Now listen to the change event of the SELECT element.
$(function(){
$("#PeriodSelection").change(function(){
var v = $(this).val();
var url=$(this).data("charturl")+'?dropdownlistReturnValue='+v;
$("#ExportDiv").load(url);
});
});
You should consider using the a view model to pass the Dropdownlist data. Why not use the DropDownListFor helper method ? It looks much clean, Mixing a lot of C# code (See all the session casting and all.) makes it kind of dirty IMHO.
look like this article.
http://www.c-sharpcorner.com/UploadFile/cd7c2e/validate-form-on-click-of-anchor-using-jquery/
but in this not mentioned how to stop button click until error completed.
so when we click on submit click and error occurred and submit click is fired on c# code i want to stop when error is displayed
If Error Occurred, that means Validation failed. So, you should return false, so that it won't fire the Button Click Code Behind Event. Else return true, so that it goes to Code Behind Click Event after Validation is completed.
So, simply...
if(Validation failed)
{
return false;
}
else
{
return true;
}
Try something like this, prevent default behavior and submit form with js after validation:
<form action="actionpage.asp" onsubmit="submitForm();" name="form">
<input type="submit" value="Submit">
</form>
function submitForm(){
if(validationfails){
return false;
}
else {
document.form.submit();
return true;
}
}
To stop the default button behaviour (i.e. submitting the form) from firing straight away you need to return false at the end of your button click handler
e.g.
$("#mybutton").click(function() {
// validate your form
$("#form1").validate({
submitHandler: function (form) {
form.submit();
},
rules: {
name: "required",
email: {
required: true,
email: true
},
field: {
required: true,
digits:true
}
}
});
return false;
});
Obviously the validation rules you create will depend on your form
I can find many different ways to add confirmation to a form submission. The issue in my case is either they submit the form anyway or they just sit there and dont do anything. Any suggestions would be appreciated. I have added events to both the form onsubmit and the button onclick, no dice. The ActionResult in this case uses HttpPostRequest to send the form data. Works great, just want to add a confirmation dialogue that works.
<script>
function SubmitConfirm(){
if (confirm("Are you sure want to submit this form?"))
return true;
else
return false;
}
<form name="Form1" method="post" action="#Url.Action("PostForm", "MyController")" id="Form1">
...
<input type="submit" value="Submit Posting" onclick="SubmitConfirm()" />
You probably want to display that dialog without reloading the page, just when your submission is successful rather than taking them to a new page or implementing some sort of conditional refresh. So you could set up your form as such...
<form name="Form1" id="Form1">
...
<input type="button" id="submit" value="Submit Posting" />
</form>
And using jQuery set up your actual submit thusly...
$(document).ready(function () {
$('#submit').click(function() { submit(); });
});
function submit() {
if (SubmitConfirm())
{
var data = $('#Form1').serialize();
$.post('MyController/PostForm', data, function(result) {
if (result === 'success') {
// just using an alert here as a placeholder
alert('Your submission has been received!');
}
});
}
}
Which means that in your controller, you'll have the following...
[HttpPost]
public ActionResult PostForm([form arguments])
{
var success = // deal with form results, return true if everything is ok
return new Content(success ? "success" : "failure");
}
To recap, you'd submit your form data, process it, and give the user feedback as to whether it was successfully processed or not without the user ever leaving the page, which also opens the door to make it easier to re-submit data if necessary and do validation, again without the user leaving the page or having to wait for the page to reload.
EDIT: Fixed typo and modified submission logic.
So I'm putting together a little registration area for my web project, here. The user inputs various strings such as "Username", "Password", etc.
I already have a bit of code set up in order to prevent duplicate Usernames or Passwords in the database. I also have a guard in place if the "Password" and "Repeat Password" fields don't match.
What I'm trying to do now is to -
1: If the user attempts to Submit data while a field is blank, it will not post.
2: Display a "Fields cannot be blank" div I've assigned "display: none" to.
I was thinking something along the lines of assigning the input fields a class of "Required", and using some sort of code such as
if == null
.show;
return false; //To prevent the rest of the function (the submit button posting to login/register) from firing.
Running into obscene problems. Anyway. Here's what I have so far.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
});
Any thoughts? At first I thought that I literally -cannot- use "class" to mark an input field, and then have that input field compared to a null value. I don't know, though.
You should use the .submit() jquery event handler on the form instead of .click() on the button. Then return false to prevent the normal form submission if needed.
Since you are trying to submit the form using $.post you should stop the default behavior of the form submit by alwasy returning false from submit button click handler.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
return false;
});
The jQuery way of preventing form submission is to use preventDefault(), like:
$("#SubmitButton").click(function (event) { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
event.preventDefault(); //And nothing else fires
return;
}
//...
});
However, since you are posting the form asynchronously when validation passes, what you really want is something more along the lines of:
$("#SubmitButton").click(function (event) { //Click Submit
event.preventDefault(); //we don't ever want to allow the default behavior
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
});
The rest of what you suggest (using a class to mark each required input field, checking them all for empty strings) is reasonable.
Be aware that because you are binding the button's click event instead of the form's submit event it is entirely possible for the user to submit your form without ever clicking on your button and triggering your validation code. For instance, by pressing return from any one of your text fields.
Also note that in this case you may find it more convenient to just use a traditional onsubmit directive on the form, like:
<form onsubmit="validateAndPost(); return false;">
<!-- inputs and buttons, etc. -->
</form>
<script>
function validateAndPost() {
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
}
</script>
Example: http://jsfiddle.net/AwxGE/
I admire your desire to use jquery, however I would advise using a normal ASP.NET ReqiredFieldValidator control. As well as making your page substantially more concise and easy to maintain, it also allows you to very simply invoke server-side validation:
public void submitbutton_click(object sender, EventArgs args){
Page.Validate();
if(Page.IsValid){
doStuff();
}
}
Please don't reinvent the wheel, and don't trust the browser to behave as you think it will.
use this -
$(document).on('click', '#SubmitButton', function () {
`enter code here`
});