Call JS method from Razor form submit - javascript

When I submit the form I want to fire-up the Javascript method written below. This JS method will send a POST request to the backend. However, in the code written below this JS method is not being fired. Can someone please help me how to correct this ?
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal", onsubmit = "submitdata" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.EMAIL, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.email, new {id ="Email", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.pwd, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.pwd, new {id="pwd", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
</div>
</div>
}
Javascript
function submitdata() {
var pwd = document.getElementById("pwd");
var email = document.getElementById("email");
$.ajax({
type: 'post',
url: '/Account/Reg',
data: {
email: email,
password: pwd
},
success: function (response) {
$('#success__para').html("You data will be saved");
}
});
return false;
}

You miss () in your onsubmit attribute;
onsubmit = "submitdata()"

As Vostrugin mentioned in his answer, you are missing () in the method call.
Here is the unobtrusive javascript way (using jQuery)
function submitdata() {
// your existing code
}
$(function(){
$("form").submit(function(e){
e.preventDefault();
submitData();
});
});
If you want to wire it with a specific button click, use a jQuery selector to get the button and bind the click event.
<input type="submit" id="myButton" value="Register"/>
and
$(function(){
$("#myButton").click(function(e){
e.preventDefault();
submitData();
});
});
With this approach, you should remove the onsubmit event from your UI markup.

Related

MVC show modal if form submit is valid

Good day! I want to create a modal that pops-up when the user clicks the submit button only if the form is valid just like this. The form validation works perfectly after click but when the form is valid, nothing happens to the form and the modal doesn't pop-up.
I have tried the solutions in here such as
$('#myModal').modal("show");
$('#myModal').dialog('open');
$('#myModal').modal();
$('#myModal').show();
$('#myModal').modal('toggle');
but still not popping up.
VIEW
<div class="col-lg-offset-4 col-lg-12">
#using (Html.BeginForm("CedulaModule", "ApplicationForm", FormMethod.Post, new { id = "contactForm", name = "contactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ApplicationCode, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ApplicationCode, new { htmlAttributes = new { #class = "form-control", #Value = #ViewBag.iAppFrmDet, #readonly = "readonly" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Firstname, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.Firstname) } })
#Html.ValidationMessageFor(model => model.Firstname, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleInitial, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.MiddleInitial, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.MiddleInitial) } })
#Html.ValidationMessageFor(model => model.MiddleInitial, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.Surname) } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Save" id="validate" class="btn btn-default"/>
</div>
</div>
}
MODAL
<div id="myModal" tabindex="-1" role="dialog" aria-hidden="true" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
<button type="button" data-dismiss="modal" aria-hidden="true" class="close">×</button>
</div>
<div class="modal-body">
#Html.Partial("CedulaPartial")
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</div>
</div>
JQUERY
<script type="text/javascript">
$('#contactForm').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$('#myModal').modal("show");
}
});
Thanks in advance.
If your form is valid save this information in any TempData and check this var on form load if data flag is exist then show your modal.
Add TempData in control post action.
TempData[“modalValid”]=true;
On form load using JavaScript.
$(document)ready(function (){
If(#TempData[“modalValid””]==true)
//display your modal
//set null in TempData
});
This code is not tested this is only for your reference.
UPDATE
After running into this post. I was able to make the code also work. Unfortunately, it was the class that was causing me error. As soon as I removed it, my code also worked. Thanks for the help.
The e.preventDefault() call is preventing the submit every time. Even when the form is valid. Try using a flag "confirmed" to make sure the e.preventDefault() is only called before the modal has been shown.
var confirmed = false;
function SubmitConfirmfunction() {
confirmed = false;
$("#contactForm").submit();
}
$(document).ready(function () {
$('#contactForm').submit(function (e) {
if (confirmed == false) {
if ($(this).valid()) {
confirmed = true;
e.preventDefault();
$('#myModal').modal("show");
}
}
});
});

Ajax Values to Controller Method

I am trying to pass values to my controller, from my view using ajax. I am relatively new to using ajax so I need some help figuring this out.
Full Page
#model ALSummary.Models.MonthReport
#{
ViewBag.Title = "Index";
}
<h2><strong>Generate Monthly Report</strong></h2>
<br />
<hr />
#Html.BeginForm("Generate", "MonthReports", FormMethod.Post, htmlAttributes: new { id = "GenerateForm" }){
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose AC:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Month:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Year:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", #class = "form-control" })
</div>
</div>
</div>
<br />
<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}
<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: #Url.Action("Generate", "MonthReports", null),
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},
});
}
</script>
Error Message:
Here is where the red squiggly lines are happenning when I receive the error message:
Your AJAX and Controller look fine... the error reported is because your javascript function can't be found (isn't present) at the time that the HTML is loaded for the Submit input (usually this is because the JS isn't loaded until after the DOM, my guess is that your script block is at the end of your body and not in the head (which is fine/preferred, just needs to be handled a bit differently)).
I typically prefer to bind events via JS rather than the HTML. Remove the onclick="sendToController()" from your HTML, and add this to your JavaScript:
$("#FormID").on('submit', function(event) {
event.preventDefault();
sendToController();
return false; // prevent submit from submitting
});
function sendToController() {
// your other code here
}
Change FormID to the ID of the form as required.

How to clear a form(s), when input changes?

My example form:
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.Server)
#Html.TextBoxFor(model => model.Server, new { #class = "form-control", id = "serverTextbox" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Username)
#Html.DropDownListFor(model => model.Username, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "usersCombo" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password)
#Html.PasswordFor(model => model.Password, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Database)
#Html.DropDownListFor(model => model.Database, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "databaseCombo" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Company)
#Html.DropDownListFor(model => model.Company, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "companyCombo" })
</div>
<div class="form-group">
<input type="submit" id="LogOn" value="Log In" class="btn btn-default" />
</div>
<div>
#Html.ValidationSummary(true)
</div>
}
So when a user changes their server entry (first input), I'm looking to implement an .change() event listener (i think), to clear the other dependant forms (drop down & input) without the use of an actual reset button.
Any help is appreciated
You can use form reset like this
$('input .form-control').on('change',function()
{
$("#form")[0].reset();
})
You can also write your custom implementation which will explicitly reset the values like
function clearForms()
{
JQuery(".form-control").attr('value',' ');
//do this for all controls and call this function
}
Options presented so far will also erase the server value, which I supose is not desirable.
A better option, not jQuery dependant, would probably be:
var serverInput = document.getElementById("serverTextbox");
var form = document.getElementsByTagName("form")[0];
serverInput.addEventListener("change", function() {
var temp = this.value;
form.reset();
this.value = temp;
});

how to send a form that contains another form

I have a form that contains another form.
the first form sends data to the action indicated in the beginform which the particular form it contains.
The second form ( contained in the first ) is a list that on change event, exchange a picture, this works .
but the first form is not sent yet.
how can I do to submit the first form normaly and the second with the javascript on change ?
#using (Html.BeginForm("VCreateCommande", "CCommande", new {id="formretouche"}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
var imagedefaut = "";
#Html.AntiForgeryToken()
<h4>Retouchephoto</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group ilnblk">
<div class="control-label col-md-2 fltleft">Type de retouche</div>
<div class="col-md-10 fltleft">
#using (Html.BeginForm("VCreateCommande", "CCommande", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownListFor(model => model.Ttyperetouche.Idtyperetouche, new SelectList(
Model.Ttyperetouches, "Idtyperetouche", "libelle", ViewData["Idtyperetouche"]), new { #onchange = "this.form.submit()" })
} </div>
<div class="fltleft imagemodele">
#if (ViewData["Idtyperetouche"] != null)
{
foreach (var typeretouche in Model.Ttyperetouches)
{
if (typeretouche.Idtyperetouche.ToString() == ViewData["Idtyperetouche"].ToString())
{
imagedefaut = typeretouche.SRCtyperetouche;
}
}
}
else
{
imagedefaut = Model.Ttyperetouches.First().SRCtyperetouche;
}
<img src="#imagedefaut" />
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Quantité</div>
<div class="col-md-10">
#Html.EditorFor(model => model.Tretouche.Quantite, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Quantite, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#{
String onclick = String.Format("Submit(this)",
Html.Encode(ViewBag.returnUrl));
}
<input type="button" id="btnsubmitretouche" value="Ajouter1" onclick="#onclick" />
<input type="submit" value="Ajouter" class="btn btn-default"/>
</div>
</div>
}
It is not valid html5 to nest forms, see the W3C HTML5 Working Draft.

How to submit a form inside Razor view by Java Script function WITHOUT redirection?

To submit form below I have to click <input type="submit" value="Save" /> which is at the bottom of form pasted below:
#model WebApplication2.Models.Person
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
This causes invoking POST Edit method in PersonController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
I also would like to have a JavaScript function which does the same( when I invoke this function) but does not redirects me to any view. Just invokes POST Edit and passes contents of the form above.
Question: How to write JavaScript function which submits the form above without redirecting me anywhere?
function SubmitForm() {}
EDIT
I tried this.
The JavaScript method is invoked when I click #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" }) (alert is displayed) but form is not submited(standard submit button works, so it is JavaScript function fault).
Form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { name="myForm", id = "myForm" })) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<p> #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" })</p>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
and the function:
function SubmitForm() {
alert("IS INVOKED");
$("#myForm").submit();
}
Easiest way I have found. :
$("#myForm").submit();
Possible duplicate of. :
ASP.Net MVC, Submit a form using javascript
You also need to name your form. In this instance myFrom is the id of your form. Something like. :
Html.BeginForm(null, null, FormMethod.Get, new { name = "myForm", id = "myForm" })

Categories