Validation in jquery for bootstrap popup - javascript

Here is my View:
#using (Html.BeginForm("SaveNewCustomer", "Dealer", FormMethod.Post, new { id = "myForm" }))
{
<div class="form-horizontal">
<div class="row">
<div class="form-group-1">
#Html.LabelFor(model => model.device.MotorType, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.MotorType, new { htmlAttributes = new { #class = "form-control required", placeholder = "Motor Type", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.PowerRating, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.PowerRating, new { htmlAttributes = new { #class = "form-control required", placeholder = "Power Rating", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.InstallationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.InstallationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Installation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.ActivationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.ActivationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Activation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.DataReceiveInterval, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.DataReceiveInterval, new { htmlAttributes = new { #class = "form-control required", placeholder = "Data receive Interval", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { #class = "form-control required", #onchange = "OnChange();" } })
</div>
<div class="form-group-1" id="HasDate">
#Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { #class = "form-control required", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } })
</div>
<button style="margin-left:33%;" id="action" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" value="SaveDeviceInfo"><strong>Save</strong></button>
</div>
</div>
}
My javascript script is
<script type="text/javascript">
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
}
});
$("#action").click(function () {
if (!$("#myForm").validate()) { // Not Valid
return false;
} else {
Save();
}
});
function Save() {
var frm = $("#myForm").serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
}
</script>
Problem is Validation not fire. In If else condition it is showing false and direct store the value in database. Could you please help me?
Is anything wrong in my code? Give me suggestions please.
Thanks in advance.

.validate() is only the initialization method.
.valid() is the method used for testing the form.
if (!$("#myForm").valid()) { ....
It's a moot point because your .ajax() function belongs inside the submitHandler option of the plugin anyway. The submitHandler callback only fires when the form is valid, thereby you can entirely eliminate your whole if/then click handler function (however you must change the button element into a type="submit").
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
},
submitHandler: function(form) { // only fires when form is valid
var frm = $(form).serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
return false;
}
});
});
NOTE: If you happen to be using the unobtrusive-validation plugin as included within your ASP framework, then the .validate() method is constructed and called automatically. If that's the case, then your call to .validate() will be ignored, and you would put any plugin options only within jQuery.validator.setDefaults().

You are missing your form tags from your html. Also, you dont have anything with the id of myform. So your trying to validate #myform in your jquery but there is no myform. You would need to add your form tags and give it an id of myform.

Related

Customize the view of Select2 Dropdown

In my view, I'm using select2Combobox as my dropdowns.
Here when the Country selection changes, I pass that selected id to the JSON result and get the results, assigning for the provinces Combobox.
When it happens, the dropdown view is changed to the square from the rounded edges.
I want to know how to add the same styles to the select2 combo boxes.
this is my code.
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Country_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownList("Country_Id", null, "Select Country", new { #class = "form-control js-dropdown js-Country", #Id = "Country", #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Country_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Province_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownListFor(model => model.Province_Id, new List <SelectListItem>(), new { #class = "form-control js-dropdown js-Province", #id = "ddlProvId" + Model.TempId, #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Province_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
Javascript
$(function () {
$('.js-Country').change(function () {
var mapperId = $(this).data('map');
setDropDownProvinces($(this).val(), mapperId)
});
});
function setDropDownProvinces(xVal, mapid) {
try {
$("#ddlProvId" + mapid).empty().trigger("changed");
$.ajax({
url: '/Account/FindProvinces',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: {
CountryId: xVal
},
success: function (data) {
if (data.Success == true) {
$("#ddlProvId" + mapid).select2({
width: '100%',
data: JSON.parse(data.items)
});
}
}
});
} catch (err) {
console.log(err.message)
}
}
This is the dropdown before selecting the country
This is after the selection.
In the success function of your ajax call try this line after mapping the result:
$("#ddlProvId" + mapid).addClass('form-control js-dropdown js-Province');
Source:
jQuery $.addClass()

C# - EditorFor functionality of ' onChangeEvent' not working

My editorfor onChangeEvent isn't working and I can't figure out why.
here is my javascript function
<script type="text/javascript">
function OnChangeEvent() {
alert("value is changed");
var compQty = $('#compQTY').val();
//do other functions here also like change button
//if decrease add below
if (compQty < #Model.comp_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
<script>
and here is my editorFor
<div class="form-group">
#Html.LabelFor(model => model.comp_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.comp_qty, new { disabled = "disabled", #Value = Model.comp_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.comp_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "compQTY" } })
#Html.ValidationMessageFor(model => model.comp_qty, "", new { #class = "text-danger" })
}
</div>
</div>
from what I have googled this should work but it is not. Can anybody help me figure out what I'm missing or what the possible solution is?

Json Result isn't working when I use db.Entry(x).State = EntityState.Modified;

I Have a view where I can edit and add new Rows on my SQL called by AddOrEdit. All I need is to press the button Submit after fill/change the fields. It calls my ActionResult on AccountController that brings me a JsonResult and my AJAX function on button click get the JsonResult to fill a Notify.js message to say that the submit was successfully done.
Problem:
When I create a new row, all works how should be but when I update a existing row, the Success message comes to my browser as raw Json.
Controller:
[HttpPost]
public ActionResult AddOrEdit(UserPortal user)
{
using (ModelEntities db = new ModelEntities())
{
try
{
if (user.UserID == 0)
{
db.UserPortals.Add(user);
}
else
{
db.Entry(user).State = EntityState.Modified;
}
db.SaveChanges();
return Json(new { success = true, message = "Submitted Successfully. Redirecting..." }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = true, message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
}
View:
#using (Html.BeginForm("AddOrEdit", "Account", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
<form id="AddOrEditUserForm">
#Html.HiddenFor(model => model.UserID)
<div class="form-group">
#Html.LabelFor(model => model.UserEmail, new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label" })
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserCompany, new { #class = "control-label" })
#Html.EditorFor(model => model.UserCompany, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserCompany)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserPosition, new { #class = "control-label" })
#Html.EditorFor(model => model.UserPosition, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserAccessLevel, new { #class = "control-label" })
#Html.EditorFor(model => model.UserAccessLevel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserAccessLevel)
</div>
<div class="form-group">
<input type="submit" name="Submit" value="Salvar" class="btn btn-primary" />
</div>
</form>
}
Javascript on View:
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
var delay = 2000; // time in milliseconds
if (data.success) {
$.notify(data.message, {
globalPosition: "top center",
className: "success",
})
setTimeout(function () {
window.location.href = '#Url.Action("AdminUsers", "Account")'; //redirect to the main page after some seconds
}, delay);
}
},
error: function (jqXHR, textStatus, errorThrown) { errorFunction(); },
});
}
return false;
}
Notify.js working when I add a new user:
image 1
When I click on submit button to update a existing user
image 2
What I've tried:
1- I add some console.log on my Submit Function and after if ($(form).valid()) I just don't receive anymore my console.log test. I think the problem is the Function and the ajax inside it.
2- On controller I gave a single JsonResult for each situation: to create I had a message saying "Created Successfully" and It worked but on the message below "Update Successfully" I got the same problem: a raw json on my screen but working perfectly on backend updating the row I requested.

relation between two dropdownlist in mvc

I have two dropdownlist,when i select an option from first one,related options show in second dropdown.i have used jquery but i dont know why it doesent work.
this is cshtml page:
<div class="form-group">
#Html.LabelFor(model => model.ProductSubGroup.ProductGroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProductGroupID", (SelectList)ViewBag.Type, "-- انتخاب ---", htmlAttributes: new { #class = "form-control",id = "rdbGroup" })
#Html.ValidationMessageFor(model => model.ProductSubGroup.ProductGroupID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductSubGroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProductSubGroupID", (SelectList)ViewBag.ProductSubGroupID, "-- انتخاب ---", htmlAttributes: new { #class = "form-control",id = "rdbSubGroup" })
#Html.ValidationMessageFor(model => model.ProductSubGroupID, "", new { #class = "text-danger" })
</div>
</div>
and this is controller
public ActionResult SelectCategory(int id)
{
var categoris = db.ProductSubGroup.Where(m => m.ProductGroup.ProductGroupID == id).Select(c => new { c.ProductSubGroupID, c.ProductSubGroupTitle});
return Json(categoris, JsonRequestBehavior.AllowGet);
}
// GET: Admin/Products/Create
public ActionResult Create()
{
ViewBag.ProductGroupID=new SelectList(db.ProductGroup,"ProductGroupID","Produ ctGroupTitle");
ViewBag.ProductSubGroupID = new SelectList(db.ProductSubGroup, "ProductSubGroupID", "ProductSubGroupTitle");
return View();
}
and this is javascript
$('#rdbGroup').change(function () {
jQuery.getJSON('#Url.Action("SelectCategory")', { id: $(this).attr('value') }, function (data) {
$('#rdbSubGroup').empty();
jQuery.each(data, function (i) {
var option = $('<option></option>').attr("value", data[i].Id).text(data[i].Title);
$("#rdbSubGroup").append(option);
});
});
});
a sample of mine
cs.html
<div class="form-group">
#Html.LabelFor(m => m.FakulteId, "Fakülte", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.DropDownListFor(m => m.FakulteId, ViewBag.Fakulte as SelectList, "Fakülte Seçiniz", htmlAttributes: new { #class = "form-control", #id = "fakulteSec", #onchange = "secim()" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.BolumId, "Bölüm", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.DropDownListFor(m => m.BolumId, ViewBag.Bolum as SelectList, "Bölüm Seçiniz", htmlAttributes: new { #class = "form-control", #id = "bolum" })
</div>
</div>
controller
public JsonResult FakulteBolumDrop(int id)
{
db.Configuration.ProxyCreationEnabled = false;
List<Bolum> bolum = db.Bolum.Where(b => b.FakulteId == id).ToList();
return Json(bolum, JsonRequestBehavior.AllowGet);
}
.js
function secim() {
var fakulteId = $('#fakulteSec').val();
//alert(fakulteId);
$.ajax({
url: '/Rektor/FakulteBolumDrop?id=' + fakulteId,
type: "POST",
dataType: "JSON",
data: { Fakulte: fakulteId },
success: function (bolumler) {
$("#bolum").html("");
$.each(bolumler, function (i, bolum) {
$("#bolum").append(
$('<option></option>').val(bolum.BolumId).html(bolum.Adi));
});
}
});
}
You have to register your change event of rdbGroup Drop Down inside the
$(document).ready(function(){
});
Otherwise it will not be fired.
use this.value or $(this).val() instead of $(this).attr('value').
Try
$('#rdbGroup').on('change',function () {// or $(document).on('change', '#rdbGroup',function (){
$.getJSON('#Url.Action("SelectCategory")', { id: this.value }, function (data) {
$('#rdbSubGroup').empty();
$.each(data, function (i,item) {// if data is json string form the replace data by $.parseJSON(data)
//console.log(item.Id); console.log(item.Title);
$('#rdbSubGroup').append($('<option>', {
value:item.Id,
text :item.Title
})); //OR you can use --- $('#rdbSubGroup').append($("<option></option>").attr("value",item.Id).text(item.Title));
});
});
});
OR
$('#rdbGroup').on('change',function () {// or $(document).on('change', '#rdbGroup',function (){
var id= this.value;
$.ajax({
url: '#Url.Action("SelectCategory")',
data: {
id: id
},
dataType: 'json',
async: false
}).done(function (data) {
$("#rdbSubGroup").html("");
$.each(data, function (i,item) {
$('#rdbSubGroup').append($("<option></option>").attr("value",item.Id).text(item.Title));
//OR $('#rdbSubGroup').append($('<option>', { value:item.Id, text :item.Title}));
});
});
});

Display Custom Errors in Html.ValidationMessageFor via jQuery

My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
#Html.LabelFor(model => model.BoolField1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
#Html.ValidationMessageFor(model => model.BoolField1, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BoolField2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { #class = "form-control", #id = "bool2" } })
#Html.ValidationMessageFor(model => model.BoolField2, "", new { #class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
First you need to correct syntax for EditorFor () it should be like following
#Html.EditorFor(model => model.BoolField1, new { #class = "form-control", #id = "bool1" })
instead of
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});

Categories

Resources