Java script confirmation form submit MVC - javascript

Im trying to call the java script confirmation form submit but it skips it. It directly calls the controller even though i want to run first the java script for confirmation.
I dont know what im doing wrong. Still new to JV Scripts.
HTML
#model WMS_Web.Models.FileMaintenance.PrincipalModels
#section Scripts {
#Scripts.Render("~/Script/FileMaintenance/CommonFunction.js")
}
#{
ViewBag.Title = "PrincipalModel";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Principal</h2>
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CompanyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CompanyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
},
function no() {
alert("no")
});'>XXX</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back", "ViewPrincipal")
</div>
Java Script
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}

You can try this:
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
...
<input type="submit" name="name" value="Save" onclick="javascript: return SubmitForm();" />
}
Javascript:
function SubmitForm() {
var r = confirm("Are you sure you want to submit?");
if (r == false) {
return false;
}
// do something
return true;
}

Related

Ajax begin form update the div

In my project, I have a main page for the document creation in DocumentsController where the user is able to change the status of the document. If the status is NEW, the user is allowed to add a new device ("part") to the document.
My goal is to insert a string to div#newDevice on ajax form submit. However, the html result is not rendered inside my main view but is rendered as a link ..../PartsBoxes/CreatePartial instead.
How could I fix that issue?
My main page part:
<input type="button" value="Add a new box" id="addNewBoxButton" class="add_new_btn" />
<input type="button" value="Add box from db" id="addDBBoxButton" class="add_existent_btn" />
<hr />
<div id="newDevice"></div>
<hr />
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$.get('#Url.Action("CreatePartial", "PartsBoxes")',{
deviceId: deviceId
},
function (data) {
$("#newDevice").html(data);
});
});
</script>
my partial view:
#model NTStock.Models.BoxPartsViewModel
#{
ViewBag.Title = "Create";
}
#using (Ajax.BeginForm("CreatePartial", new AjaxOptions { UpdateTargetId = "newDevice" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.DocumentId)
<div class="form-group">
#Html.LabelFor(model => model.InternalName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InternalName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.InternalName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SerialNumber, "", new { #class = "text-danger" })
</div>
</div>
//......///
<div class="form-group deviceManipulations">
#Html.LabelFor(model => model.DeinstallationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DeinstallationDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DeinstallationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save box" class="btn btn-default" />
</div>
</div>
</div>
}
and the method:
[HttpPost]
[ValidateAntiForgeryToken]
public ContentResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Content("string to return");
}
as a result I get:
Firstly you should be sure jquery.unobtrusive-ajax is loaded in your page and you dont use jquery 1.9 version because it doesnt support jquery live methods.
Reference : http://jquery.com/upgrade-guide/1.9/
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then I would suggest to use jquery .load() function to load partial view into target element and use JsonResult instead of ActionResult to achieve your goal like following.
// jquery
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$("#newDevice").load('#Url.Action("CreatePartial", "PartsBoxes")' + "/" deviceId );
});
</script>
//controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Json(new { data = "string to return" });
}

How to redirect to POST ActionResult from jQuery?

I tried to add toastr notification in my code. Before adding it, it perfectly works fine. But when I tried to add toastr notification after jQuery validation, it shows that the record was successfully performed but it won't redirect or save data like previous. It seems that the jQuery didn't forward the viewModel data to the POST method. Following is my codes:
#model ESportsScreening.ViewModel.ScreeningFormViewModel
#{
ViewBag.Title = "New Screening ";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Screening</h2>
#using (Html.BeginForm("Create", "Screenings", FormMethod.Post, new { id = "createForm" }))
{
<p class="alert alert-info">All fields are <strong>required</strong></p>
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.TeamA)
#Html.TextBoxFor(m => m.TeamA, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.TeamA)
</div>
<div class="form-group">
#Html.LabelFor(m => m.TeamB)
#Html.TextBoxFor(m => m.TeamB, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.TeamB)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Date)
#Html.TextBoxFor(m => m.Date, new { #class = "form-control", placeholder = "eg 1 Jan 2018" })
#Html.ValidationMessageFor(m => m.Date)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Time)
#Html.TextBoxFor(m => m.Time, new { #class = "form-control", placeholder = "eg 24:00" })
#Html.ValidationMessageFor(m => m.Time)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Ticket)
#Html.TextBoxFor(m => m.Ticket, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Ticket)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Competition)
#Html.DropDownListFor(m => m.Competition, new SelectList(Model.Competitions, "Id", "Name"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Competition)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Description)
#Html.TextAreaFor(m => m.Description, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Description)
</div>
<button class="btn btn-primary">Save</button>
}
#section scripts
{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#createForm").submit(function (e) {
e.preventDefault();
$('#createForm').validate();
if ($('#createForm').valid()) {
toastr.success("Screening recorded succesfully!");
} else {
toastr.fail("Something unexpected happened..");
}
});
});
</script>
}
What are the changes required in my jQuery so that it can forward me to the POST method of ScreeningController and Create(viewModel)?
You need to remove e.preventDefault();. It preventing to post on server.
$("#createForm").submit(function (e) {
$('#createForm').validate();
if ($('#createForm').valid()) {
toastr.success("Screening recorded succesfully!");
} else {
toastr.fail("Something unexpected happened..");
}
});

how i can focus on the return form that have validation errors

I am working on an asp.net mvc-5 web application , and i have the following contact us form at the middle of the contact Us view:-
<div class="col-sm-8 col-sm-push-4">
<h2>Contact Us1</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#if (TempData["message"] != null)
{
<div class="alert alert-success">
×
<strong> #TempData["message"].</strong>
</div>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } }) <span style="color:red">*</span>
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Message, new { #cols = 60, rows = 10, #class = "form-control" })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-success" /><span id="progress" class="text-center" style="display: none;">
<img src="~/img/ajax-loader.gif" />
</span>
</div>
</div>
</div>
}
</div>
and here the Get and Post action methods:-
public ActionResult Contact()
{
ViewBag.Title = "Contact";
ViewBag.Description = "Home";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contact(Contact c)
{
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
//code goes here
TempData["message"] = string.Format("Your Feedback has been submitted. Thanks");
return RedirectToAction("Contact");
}
ModelState.AddModelError("", "Cannot submit you Contact Form, please review the Contact Form for any missing info.");
return View(c);
}
now i am facing this problem:-
1. since the contact us form appear on the middle of the page, so users on small sized screens , might submit the form , then the Post request failed (model validation failed), where the contact us form will be rendered again with the validation errors shown, but users might not see the form, since by default the browser will move to the top. while on large screen the user can still see the form , but on mobile browser users might miss that there are errors on the form that they have just submit.
so i am thinking if there is a way to do this:-
if the form is rendered with errors, to force the browser (using jquery form example) to go to the form , so that users can see the validation errors ?
can anyone adivce on this please ?
Firstly you #Html.ValidationSummary() code should be inside the form tags in order for it to work correctly.
You can use javascript to scroll to the form in the view. Give the form (or an element near where you want to scroll to) an id attribute
#using (Html.BeginForm("Contact", "yourControllerName", FormMethod.Post, new { id = "form" }))
Then add the following script (inside document.ready)
if ('#ViewBag.HasError') {
location.href = '#form'; // or location.hash = '#form';
}
and modify the POST method to add the ViewBag property if there are errors
ModelState.AddModelError("", "Cannot ..... info.");
ViewBag.HasError = true; // add this
return View(c)
Side note: Not tested, but you should also be able to use
if ('#ViewContext.ViewData.ModelState.Values.SelectMany(v => v.Errors).Any()') {
as an alternative to using a ViewBag property.
Put #Html.ValidationSummary(false, "", new { #class = "text-danger" }) at the top of your page. Change true to false to show all property level errors.

javascript click function not working in asp.net mvc

I'm having following asp.net mvc 5 web application view page , Prevously its worked very well.
#model project_name.Models.SearchBrochureVM
#{
ViewBag.Title = "Brochure_Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Product Brochure Generation</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group"></div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Category, Model.CategoryList, "Select the category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Country, Model.CountryList, "Select the country", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Product, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Product, Model.ProductList, "Select the subsidary", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="search" type="button" class="btn btn-success submit">Select Information</button>
</div>
</div>
</div>
}
<form id="brochureform">
<table class="table">
<thead>
<tr>
<th>Property_ID</th>
<th>IsChecked</th>
<th>Property Tile</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
</form>
<table id="template" class="table" style="display: none;">
<tr>
<td>
<span></span>
<input type="hidden" name="[#].Property_ID" />
</td>
<td>
<input type="checkbox" name="[#].IsChecked" value="true"/>
<input type="hidden" name="[#].IsChecked" value="false"/>
</td>
<td>
<span></span>
</td>
</tr>
</table>
<div style="width:50%; float:left;text-align:left"><button id="resetborchure" type="button" class="btn btn-warning submit">Reset Brochure</button> </div>
<div style="width:50%; float:left;text-align:right"><button id="createborchure" type="button" class="btn btn-danger submit">Create Brochure</button> </div>
<script type="text/javascript">
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
var type = $('#Type');
var category = $('#Category');
var country = $('#Country');
var product = $('#Product');
$('#search').click(function () {
var url = '#Url.Action("FetchProductProperties")';
$.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), product: product.val() }, function (data) {
$.each(data, function (index, item) {
var clone = $('#template').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
var cells = clone.find('td');
cells.eq(0).children('span').text(item.ID);
cells.eq(0).children('input').val(item.ID);
cells.eq(1).children('input').first().prop('checked', item.CheckOrNot)
cells.eq(2).children('span').text(item.Name);
$('#table').append(clone.find('tr'));
});
});
});
$('#createborchure').click(function () {
var data = $('#brochureform').serialize();
var url = '#Url.Action("Create_Brochure", "Brochure")';
//$.get(url, data, function (result) {
// window.location = url;
//});
$.ajax({
url: url,
type: 'GET',
data: data
})
.success(function (response) {
});
});
$('#resetborchure').click(function () {
table.empty();
});
</script>
}
Above view have two buttons called Reset Brochure and Create Brochure
Once I click Reset Brochure button its clear the table in that view and once I select Create Brochure its redirect to another view.
previously these two functions worked very well , but I cannot understand this isn't give any response once I click these buttons.
Since your wanting to redirect to another method (passing the values of the form controls in the table) there is no reason to use ajax, and instead you should just do a normal submit.
Replace the <form id="brochureform"> element with
#using (Html.BeginForm("Create_Brochure", "Brochure", FormMethod.Get))
{
<table class="table">
<thead>
....
</thead>
<tbody id="table"></tbody>
</table>
<input type="submit" value="CreateBrochure" />
}
and remove the <button id="createborchure" ...>Create Brochure</button> element and its associated script. This will now make a GET call to your public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model) method
However this will also create a really ugly url and there is a risk that you will exceed the query string limit and throw an exception. In general GET methods should never have parameters which are collections.
From the DotNetFiddle you provided in chat, its unclear how your using the data you pass to the method (your create a variable string ids but then never actually use it. Assuming you do actually need it for the view you return in that method, I would suggest adding another POST method to avoid the issues above.
[HttpPost]
public ActionResult Initialize_Brochure(IEnumerable<ProductsPropertiesVM> model)
{
IEnumerable<int> selectedIDs = model.Where(x => x.IsChecked).Select(x => x.Property_ID);
string ids = string.Join(",", selectedIDs);
return RedirectToAction("Create_Brochure", new { id = ids });
}
and change the Create_Brochure() method to
public ActionResult Create_Brochure(string id)
{
....
}
and finally modify the BeginForm() to
#using (Html.BeginForm("Initialize_Brochure", "Brochure", FormMethod.Post))
This means you url will simply be something like
/Brochure/Initialize_Brochure/2,4,5 depending on the checkboxes you select

Updating part of view after submitting a post using jquery ajax in asp.net mvc

I'm working on a form in my application, which I want to post using ajax. The posting works fine and my controller receives the data, but I'd like to just post a success message back to my view instead of refreshing the entire page. Do I have to return a partial view with the information for this, or can I just return a message from my controller? I can't seem to figure out how to do this properly.
<div class="panel panel-gray">
<div class="panel-body">
<form method="POST" action="#Url.Action("SaveWellDetails", "WellManagement")" id="wellform" class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.Id, new { #class = "col-md-3 control-label"})
<div class="col-md-9">
#Html.TextBoxFor(m => m.Id, new { #class = "form-control", disabled = "disabled", id = "WellId", name = "WellId" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Location, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Location, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellNumber, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellNumber, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellType, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellType, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.SpudDate, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.SpudDate, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<input type="submit" id="submit" class="btn btn-primary" value="Save Changes" />
<div class="pull-right" id="wellsavesection">
<div id="processing_small" hidden="hidden">
<img src="~/Content/Kendo/Flat/loading_2x.gif" />
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#wellform').submit(function () {
console.log("wellId = " + $("#WellId").val());
$("#processing_small").show().hide().fadeIn('slow');
$.ajax({
url: '#Url.Action("SaveWellDetails", "WellManagement")',
type: "POST",
dataType: "json",
data: {
wellId: $('#WellId').val(),
name: $('#Name').val(),
location: $('#Location').val(),
wellNumber: $('#WellNumber').val(),
wellType: $('#WellType').val(),
spudDate: $('#SpudDate').val()
},
error: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + msg.statusText + '</div>').fadeIn('slow');
},
success: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Form Saved.</div>').fadeIn('slow').delay(1500).fadeOut();
}
});
});
});
</script>
Here's my controller:
[HttpPost]
public ActionResult SaveWellDetails(string wellId, string name, string location, string wellNumber, string wellType, DateTime spudDate)
{
try
{
var wellConctract = new WellContract
{
Id = Convert.ToInt32(wellId),
Name = name,
Location = location,
WellNumber = wellNumber,
WellType = wellType,
SpudDate = spudDate
};
WellService.UpdateWell(wellConctract);
}
catch (Exception e)
{
Log.Error(e);
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
}
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
Simply add return false; the end of the $('#wellform').submit(function () {... (after the ajax function, not inside it) and it should work, I tried it out in jsfiddle.
What this does it prevent the form from submitting.
you doesn't need a partial view to do that, your page will refresh each submit because it doing the usual event, try add event.preventDefault() http://api.jquery.com/event.preventdefault/
$('#wellform').submit(function (ev) {
ev.preventDefault();
// put your code below here
.....
});

Categories

Resources