JQueryValidation with MVC 4 not validating on blur - asp.net-mvc

I am beating my head on the wall for hours with MVC 4 and jQuery validation to validate the first first on blur. I have tried attaching the validation to the entire form AND to the individual element (first field) to no avail. If I add an alert() into the blur event it seems to fire but no validation of the required field. I have additional validations to add after the required is working but haven't gotten to them yet. I don't know that it is a problem with the MVC 4. JQueryvalidate is v1.10. I have also tried setting up the validator and then calling .valid() on the element I want validated using the .blur and still not validation that I can see.
$(function () {
$('#productionOrder').focus();
$.validator.addMethod("cMinLength", $.validator.methods.minlength,
$.format("Must contain as least {0} chars"));
$.validator.addClassRules("productionOrder", { cMnLength: 3 });
$('#myForm').validate({
onkeyup: false,
//onfocusout: false,
errorClass: 'fieldError'
//rules: {
// productionOrder: "required number",
// tc: "required",
// dn: "required"
//}
});
$("#towCount").bind("change keyup", function () {
$form.validate().element("#towCount");
});
//$('#productionOrder').validate({
// //onkeyup: false,
// onfocusout: false,
// errorClass: 'fieldError',
// rules: {
// productionOrder: {
// required: true
// }
// }
//});
});
And the .cshtml
#model FiberLine2.ViewModels.Creel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<style>
.fieldError {
border-color: red;
border-width: medium;
}
.input-label {
font-size: 13px;
width: 130px;
height: 30px;
display: inline-block;
}
</style>
</head>
<body>
<form id="myForm">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
<!-- app header -->
<label>#Resources.Strings.User: </label>
<label>#User.Identity.Name</label>
</div>
<fieldset>
<legend>#Resources.Strings.Creel #Resources.Strings.Load</legend>
<div>
<div id="errorDiv"></div>
<hr />
#Html.Label(#Resources.Strings.ProductionOrder, new { #class = "input-label lock" })
<input type="text" id="productionOrder" name="productionOrder" class="required" maxlength="4" />
<br />
<label class="input-label lock">#Resources.Strings.Tow #Resources.Strings.Count</label>
<input type="text" id="towCount" name="tc" class="required" size="5" maxlength="5" value="299" />
<br />
<label class="input-label lock">#Resources.Strings.Batch #Resources.Strings.Sequence</label>
<input type="text" id="doffNumber" name="dn" size="5" maxlength="5" value="1" />
<br />
<label class="input-label">#Resources.Strings.Creel #Resources.Strings.Position</label>
<input type="text" id="creelPosition" name="cp" size="5" maxlength="5" />
<br />
<label class="input-label">#Resources.Strings.Batch #Resources.Strings.ID</label>
<input type="text" id="creelNumber" name="cn" size="7" maxlength="7" />
<br />
<hr />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
</body>
</html>

Can you try this instead?
var settngs = $.data($('#myForm')[0], 'validator').settings;
settngs.onkeyup = false;

Related

when submit button is click the input data has been disappear how can I rectify?

when submit button is clicked the input data is disappear in html How can I rectify the problem?
<html>
<head>
<title>hhhh</title>
</head>
<body>
<form id="form">
<input type="text" id="username" placeholder="username" />
<input type="submit" id="btn" />
</form>
</body>
<script>
var a = document.getElementById("username");
var b = document.getElementById("btn");
b.addEventListener("click", () => {
console.log(a.value);
});
</script>
</html>

Render html form into main html page using AngularJS app method

I am very new to AngularJS and trying to understand how AngularJS can use along with ASP.NET-MVC5 application. In my first attempt I want to run AngularJS app from basic HTML page (in my case index.html) where app holding form template in html format, also I have add global variable, controller, service via factory and directives but I cannot manage to run this app 'employee-form' inside index.html. In order to test if angularJS is initialize and working properly, I have added very basic angularjs code inside in html and it works.. I am not sure where I have done mistake
AngularFormsApp.js (global variable)
var angularFormsApp = angular.module('angularFormsApp', []);
efController.js
angularFormsApp.controller('efController',
function efController($scope, efService) {
$scope.employee = efService.employee;
});
efService.js
angularFormsApp.factory('efService',
function () {
return {
employee: {
fullName: "Khurram Zahid",
notes: "The ideal employee, just don't mess with him",
department: "IT Development",
perkCar: true,
perkStock: false,
perkSixWeeks: true,
payrollType: "none"
}
}
});
efDirective.js
angularFormsApp.directive('employeeForm',
function () {
return {
restrict: 'E', //E stands for element, meaning we want to use this directive as element
templateUrl: '~/App/EmployeeForm/efTemplate.html'
}
});
efTemplate.html (form)
<div class="form-group">
<label for="fullName">Name</label>
<input type="text" id="fullName" name="fullName" class="form-control" />
</div>
<div class="form-group">
<label for="notes">Notes</label>
<input type="text" id="notes" name="notes" class="form-control" />
</div>
<div class="form-group">
<label for="department">Department</label>
<select id="department" name="department" class="form-control">
<option>Engineering</option>
<option>Marketing</option>
<option>Finance</option>
<option>IT Development</option>
</select>
</div>
<br/>
<span><b>Perks</b></span>
<div class="checkbox">
<label><input type="checkbox" value="perCar"/>Company Car</label>
</div>
<div class="checkbox">
<label><input type="checkbox" value="perkStock" />perk Stock</label>
</div>
<div class="checkbox">
<label><input type="checkbox" value="perkSixWeeks" />perk Six Weeks</label>
</div>
<input type="submit" value="Submit Form" />
index.html
<!DOCTYPE html>
<html>
<head >
<title>Angular JS</title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="App/AngularFormsApp.js"></script>
<script src="App/EmployeeForm/efController.js"></script>
<script src="App/EmployeeForm/efService.js"></script>
<script src="App/EmployeeForm/efDirective.js"></script>
</head>
<body ng-app="angularFormsApp">
<div class="AngularJSTestBlockCode">
<div>
<input type="text" ng-model="name" />
<br />
<h1>Hello {{name}}</h1>
</div>
<br /><br />
<div>
{{458/8}}
</div>
</div>
<div>-------------------------------------------------------</div> <br/><br/>
<div ng-controller="efController">
<employee-form>????????????????????
</div>
You need a route provider to render your html page. Here is your example
.config(['$stateProvider',function($stateProvider) {
$stateProvider.state('dashboard', {
url:'/dashboard',
templateUrl: 'views/dashboard/main.html',
})
.state('dashboard.create-example',{
templateUrl:'views/example/create.html',
url:'/create-example',
controller:'Ctrl'
})
then in your controller(efController.js) put this $state.transitionTo('dashboard.create-example'); to render your page to any html you want

Why does my partial view not working?

I created a partial view and I use this partial to another view that it inherit from a _layout m code is true and doesn't have a bug, but when I click on submit it shows this message : (The resource cannot be found). I can't trace this error . please help me . thanks
This is my news.Cshtml:
#model MPortal.Models.WebSite_OpinionDB
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Body{
#Html.Partial("CreateOpinion")
#Html.Action("CreateOpinion", "User")
}
And this is my _Layout.cshtml :
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/Theme/css/bootstrap.css" rel="stylesheet">
<link href="~/Content/CssFramework.css" rel="stylesheet" />
#RenderSection("CSS", required: false)
</head>
<body>
#RenderSection("Body", required: false)
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/modernizr-2.5.3.js"></script>
<script src="~/Theme/js/bootstrap.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
And this is my Partialview :(CreateOpinion.cshtml)
#model MPortal.Models.WebSite_OpinionDB
#section Body{
<div class="" style="float: right; width: 75%">
#Html.Raw(Session["Right"])
#using (Html.BeginForm())
{
<div class="rateit" style="float: right; width: 25%">
<input type="text" maxlength="100" value="name" class="form-control" name="Values" id="NameFamily" />
<br />
<input type="text" maxlength="100" value="email" class="form-control" name="Values" id="Email" />
<br />
#Html.TextAreaFor(x => x.OpinionText, new { #class = "form-control", #placeholder = "opinion" })
<br />
<button class="btn btn-primary" type="submit">submit</button>
</div>
}
<div class="" style="width: 20%; height: 625px; border: 1px solid black; float: left">
#Html.Raw(Session["Left"])
</div>
</div>
<div class="" style="float: right; width: 75%">
#if (ViewData["Success"] != null)
{
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
#(ViewData["Success"] != null ? ViewData["Success"].ToString() : "")
</div>
}
#if (ViewData["UnSuccess"] != null)
{
<div class="alert alert-danger bs-alert-old-docs">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
#(ViewData["UnSuccess"] != null ? ViewData["UnSuccess"].ToString() : "")
</div>
}
</div>
}
and this is my action of partial view :
[ChildActionOnly]
public ActionResult CreateOpinion(MPortal.Models.WebSite_OpinionDB saveop, FormCollection frm)
{
if (!string.IsNullOrEmpty(frm["Values"]))
{
int mtID = (int)MPortal_CL.Globals.GetParam("MetaDataID", 0);
MPortal.Models.WebSite_OpinionDB op = new MPortal.Models.WebSite_OpinionDB();
String[] texts = frm["Values"].Split(',');
.....
.......
}
Remove attribute [ChildActionOnly] and if this does not work please use the overloaded version
#using (Html.BeginForm("CreateOpinion","ControllerName"))

How to display wrong username password on login form ?

I am developing the MVC application.
I have designed the login form.
when user enters the proper username and password then, it redirect to next page, but when user put wrong username or password I want to display the message on the login form, how to do it.
This is the code of method in controller...
[HttpPost]
public ActionResult LoginUser(FormCollection oFormCollection)
{
string userName = oFormCollection["username"];
string password = oFormCollection["password"];
bool IsAccountPerson = false;
var validEmployee = (from e in db.Employees
where e.UserName == userName && e.Password == password
select e).ToList();
if (validEmployee.Count() == 1)
{
foreach (var v in validEmployee)
{
oEmployee = v;
Session["LoggedEmployee"] = oEmployee;
Session["loggedEmpId"] = oEmployee.Id;
if (oEmployee.DesignationType == "Account")
{
IsAccountPerson = true;
}
else
{
IsAccountPerson = false;
}
}
if(IsAccountPerson)
return RedirectToAction("PaymentAdviceListForAccounts", "Account");
else
return RedirectToAction("Index", "PaymentAdvice");
}
else
return PartialView("Index");
}
and this is my view Code....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="#Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<title></title>
</head>
#using (Html.BeginForm("LoginUser","Login",FormMethod.Post))
{
#*<div style="margin:15% 20% 20% 30%; width:35%;min-height:25%;border:1px #ACACAC solid;">*#
<div class="container-fluid" style="padding-left:0px; margin-top:165px; margin-left:140px;">
<div class ="span3">
<label style="font-size:15px; color:#666666; margin-top:5px;">Username</label>
</div>
<div class ="span6">
<input type="text" id="username" name="username" style="height:20px; width:100%;" />
</div>
<div class ="span3">
<label style="font-size:15px;color:#666666; margin-top:5px; ">Password</label>
</div>
<div class ="span6">
<input type="password" id="password" name="password" style="height:20px; width:100%;"/>
</div>
<div class="span6" style="padding-left:15px;">
<input type="submit" name="submit" value="Login" class="btn btn-primary" style="margin-right:10px; height:30px; font-size:14px; width:55px;" />
<input type="button" name="Login" value="Cancel" class="btn btn-primary" style="margin-right:20px; height:30px; font-size:14px; width:55px; padding-left:5px; padding-right:5px;" />
</div>
</div>
</div>
</div>
</div>
}
</body>
</html>
create new model or use TempData.
here is the example using TempData.
http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html

jquery use of :last and val()

I'm trying to run the code from http://jsfiddle.net/ddole/AC5mP/13/ on my machine and the approach I've use is below or here.
Do you know why that code doesn't work on my machine. Firebug doesn't help me and I can't solve the problem. I think that I need another pair of eyes :(((
In firebug,console tab i don't get any error message. The problem is that I can't get the value of that input from the dialog box, after I press save button. The $('input:last').val() seems to be empty
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Modal form</title>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" >
jQuery(function($) {
$('.helpDialog').hide();
$('.helpButton').each(function() {
$.data(this, 'dialog',
$(this).next('.helpDialog').dialog({
autoOpen: false,
modal: true,
width: 300,
height: 250,
buttons: {
"Save": function() {
alert($('.helpText:last').val());
$(this).dialog( "close" );
},
Cancel: function() {
$(this).dialog( "close" );
}
}
})
);
}).click(function() {
$.data(this, 'dialog').dialog('open');
return false;
});
});
</script>
</head>
<body>
<span class="helpButton">Button</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 2</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 3</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 4</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 5</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div> </body>
Refer LIVE DEMO
To display the text on save, I have modified your line alert($('.helpText:last').val()); to this alert($('.helpText', this).val());
I have added one more dependencies on fiddler,
http://code.jquery.com/ui/1.8.21/jquery-ui.min.js
Now its working as expected.
HTML:
<span class="helpButton">Button</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 2</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 3</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 4</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
<span class="helpButton">Button 5</span>
<div class="helpDialog">
<input type="text" class="helpText" />
</div>
JS:
jQuery(function($) {
$('.helpDialog').hide();
$('.helpButton').each(function() {
$.data(this, 'dialog',
$(this).next('.helpDialog').dialog({
autoOpen: false,
modal: true,
width: 300,
height: 250,
buttons: {
Save: function() {
alert($('.helpText', this).val());
$(this).dialog( "close" );
},
Cancel: function() {
$(this).dialog( "close" );
}
}
})
);
}).click(function() {
$.data(this, 'dialog').dialog('open');
return false;
});
});

Resources