I'm using bootstrap in my application.
I'm creating dropdown and textbox controls dynamically based on a count and applying validation to those controls.But validation is not working for those textbox controls alone.
Here is my code:
Default.aspx.cs
public partial class DefaultClass
{
public int ddlCount{ get; set; }
public int txtCount{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
Default.aspx
<div class="form-horizontal">
<%if (ddlCount > 0)
{
for(int i=0;i<ddlCount ;i++)
{%>
<div class="control-group">
<label class="control-label">DropDown <%=i++%>
</label>
<div class="controls">
<select data-val="true" data-val-required="Field is required" name="">
<option value="">--Select--</option>
<option value=1>Value1</option>
<option value=2>Value2</option>
</select>
</div>
</div>
<%
}
}
if (txtCount> 0)
{
for(int i=0;i<txtCount;i++)
{%>
<div class="control-group">
<label class="control-label">Textbox<%=i++%>
</label>
<div class="controls">
<input type="text" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
</div>
</div>
<%}
}%>
</div>
<button id="btnSubmit" class="btn btn-success" onclick="Submit();">
Submit</button>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
} else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
} else {
error.insertAfter(element);
}
};
}
function Submit() {
if (!$('#Form1').valid()) {
return false;
}
}
</script>
I'm using js/jquery.validate.min.js , js/uncompressed/jquery.validate.js and js/uncompressed/jquery.validate.unobtrusive.js .
Validation is not working for textbox controls alone.
Please help me out.
try by including name attribute may it work
<input type="text" name="text_box" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
Related
I have a view as follows
#if(Model.Is_Prefix_Checked == 1)
{
<div class="row mb-2">
<div>
<div class="col-md-1" style='align-content:center;'>
<input type="checkbox" class="largerCheckbox" id="Is_Prefix_Checked" name="IsPrefixChecked" checked="checked" >
</div>
</div>
<label class="col-sm-2 col-form-label">Prefix</label>
<div class="col-sm-3">
<select asp-for="EmployeePrefix" class="form-control" asp-items="#ViewBag.prefix" >
</select>
<span asp-validation-for="EmployeePrefix" class="text-danger" ></span>
</div>
</div>
}
else
{
<div class="row mb-2">
<div>
<div class="col-md-1" style='align-content:center;'>
<input type="checkbox" class="largerCheckbox" id="Is_Prefix_Checked" name="IsPrefixChecked">
</div>
</div>
<label class="col-sm-2 col-form-label">Prefix</label>
<div class="col-sm-3">
<select asp-for="EmployeePrefix" class="form-control" asp-items="#ViewBag.prefix">
</select>
<span asp-validation-for="EmployeePrefix" class="text-danger"></span>
</div>
</div>
}
when i click on the checkbox i am getting the value , but when i come back to the page the checkbox is already clicked and now when i try to update the form the already clicked checkbox value are showing as 0 instead of 1 .
I need to do this for more than for 20 fields in each page
My jquery is as follows
<script>
window.onload = function () {
func2();
}
</script>
<script>
function func2() {
window.onload=function()
{
const checkBoxes=document.querySelectorAll("input[type='checkbox']");
const checkBoxes = document.querySelectorAll
for(var i=0; i < checkBoxes.length; i++)
{
if (this.checked)
{
$(this).attr("value", "1");
} else
{
$(this).attr("value", "0");
}
}
}
}
</script>
<script>
// this is the scrpt for checkbox
$(document).on("click", "[type='checkbox']", function (e) {
if (this.checked) {
$(this).attr("value", "1");
} else {
$(this).attr("value", "0");
}
});
</script>
I need to clear filter after search
Here is my index.cshtml
<form method="post" id="form">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchNom" value="#ViewData["sNom"]?.ToString()" class="form-control" id="nom" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchPrenom" value="#ViewData["sPrenom"]?.ToString()" id="prenom" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchEmail" value="#ViewData["sEmail"]?.ToString()" id="email" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchTelephone" value="#ViewData["sTelephone"]?.ToString()" id="telephone" />
</div>
</div>
<div class="col-md-2">
<p>
<input type="submit" value="Search" class="btn btn-primary" />
<button class="btn" type="reset" id="reset" onclick="Reset()"><i class="fa fa-trash"></i></button>
</p>
</div>
</div>
</form>
and then the action Index:
public string searchNom { get; set; }
public string searchPrenom { get; set; }
public string searchEmail { get; set; }
public string searchTelephone { get; set; }
public async Task<IActionResult> Index(string searchNom, string searchPrenom, string searchEmail, string searchTelephone, int? pageNumber, string currentFilter)
{
if (searchNom != null || searchPrenom != null || searchEmail != null || searchTelephone != null)
{
pageNumber = 1;
}
var personnels = from s in _context.personnels
select s;
if (!String.IsNullOrEmpty(searchNom) || !String.IsNullOrEmpty(searchPrenom) || !String.IsNullOrEmpty(searchEmail) || !String.IsNullOrEmpty(searchTelephone))
{
personnels = personnels.Where(s => s.Nom.Equals(searchNom) || s.Prenom.Equals(searchPrenom) || s.Email.Equals(searchEmail) || s.Telephone.Equals(searchTelephone));
ViewData["sNom"] = searchNom ;
ViewData["sPrenom"] = searchPrenom;
ViewData["sEmail"] = searchEmail;
ViewData["sTelephone"] =searchTelephone ;
}
else
{
ViewData["sNom"] = "";
ViewData["sPrenom"] = "";
ViewData["sEmail"] = "";
ViewData["sTelephone"] = "";
}
int pageSize = 20;
return View(await Pagination<PersonnelModel>.CreateAsync(personnels.AsNoTracking(), pageNumber ?? 1, pageSize));
}
js code:
<script>
function Reset() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
}</script>
Now the problem ,the button reset dosen't work ther is an exception Uncaught TypeError: Cannot set property 'selectedIndex' of null
at Reset ((index):357)
at HTMLButtonElement.onclick ((index):107)
Is there any way how to make "reset" button working on form data values in same time please?
Thank you very much in advance for any kind of help.
Welcome to SO.
The code above can't be executed as we don't have the _context variable, nor the PersonelModel class.
The way you use ViewData to initially populate the form seems a little shady - I'd make sure I pass the view model instead. I appreciate that this is not the issue here.
Answering the actual question, I'd start with wrapping the script functions with
document.addEventListener("DOMContentLoaded", function(){
// Handler when the DOM is fully loaded
});
or have a look here
Instead of depending on onclick attribute, have a look at .click() function from jQuery library, have a look here
Using the above, your code will look something like:
$("#submit-button").click(function() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
});
given you added submit-button id to your button.
I found the solution finally ,i added this document.forms["form"].submit(); also
<script>
function Reset() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
document.forms["form"].submit();
}</script>
I am working on a project that uses ASP.NET MVC and AngularJS, i am
trying to use time input type to set and get time from database i am
using code first approach , my question is i want to get the time from
database then bind it to input time, i inserted the time successfully
to the database but i have problem i can not bind it with the input
time control.
**Model**
public class Branches
{
public int Branch_ID { get; set; }
public string Branch_Name { get; set; }
public string Branch_Address { get; set; }
public string Branch_email { get; set; }
public string Branch_Notes { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:hh\:mm}")]
public TimeSpan Branch_TimeFrom { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:hh\:mm}")]
public TimeSpan Branch_TimeTo { get; set; }
}
**Controller**
public class BranchesController : Controller
{
private IRepositoryBase<Branches> BrancheRepository;
public BranchesController()
{
this.BrancheRepository = new BranchesRepository(new HrmDBContext());
}
public BranchesController(IRepositoryBase<Branches> brancheRepository)
{
this.BrancheRepository = brancheRepository;
}
// GET: Branches
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Create(Branches branch)
{
try
{
if (ModelState.IsValid)
{
BrancheRepository.Create(branch);
//var branches = BrancheRepository.GetAll();
//return Json(new
//{
// d = true,
// pv = RazorToString(this, "~/views/Branches/list.cshtml", branches),
//}, JsonRequestBehavior.AllowGet);
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
catch (DataException dex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem
persists contact your system administrator.");
return Json(new { success = false });
}
// return View(branch);
}
[HttpPost]
public JsonResult Edit(Branches branch)
{
try
{
if (ModelState.IsValid)
{
BrancheRepository.Update(branch);
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
catch (DataException dex )
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
return Json(new { success = false });
}
}
}
**FetchBranchData.js**
var app = angular.module('myapp', []);
app.service("myService", function ($http) {
//get All Branches
this.getAllBranches = function () {
return $http.get("Branches/GetAllBranches");
};
//$http.get(url).then(response) {
// var data = response.data;
// data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
// data.Branch_TimeTo = new Date(data.Branch_TimeTo);
// $scope.data = data;
//});
//add new Branch
this.save = function (Branch) {
var request = $http({
method: 'post',
url: '/Branches/Create',
data: Branch
});
return request;
};
//update Employee records
this.update = function (Branch) {
var updaterequest = $http({
method: 'post',
url: '/Branches/Edit',
data: Branch
});
return updaterequest;
};
});
app.controller("branchcontroller", function ($scope, myService) {
getAllBranches();
function getAllBranches() {
var getData = myService.getAllBranches();
getData.then(function (response) {
$scope.Branches = response.data;
}, function (error) {
console.log(error);
alert('Error in getting records');
});
};
//save Branch data
$scope.save = function () {
debugger
var Branch = {
Branch_Name: $scope.Branch_Name,
Branch_Address: $scope.Branch_Address,
Branch_email: $scope.Branch_email,
Branch_Notes: $scope.Branch_Notes,
Branch_TimeFrom: moment($scope.Branch_TimeFrom).format('HH:mm:ss'),
Branch_TimeTo: moment($scope.Branch_TimeTo).format('HH:mm:ss'),
Branch_Manager: $scope.Branch_Manager,
Branch_Phone: $scope.Branch_Phone,
saturday: $scope.saturday
};
var saverecords = myService.save(Branch);
saverecords.then(function (response) {
if (response.data.success === true) {
getAllBranches();
alert("Branch added successfully");
$scope.resetSave();
}
else { alert("Branch not added."); }
},
function () {
alert("Error occurred while adding branch.");
});
};
//reset controls after save operation
$scope.resetSave = function () {
$scope.Branch_Name = '';
$scope.Branch_Address = '';
$scope.Branch_email = '';
$scope.Branch_Notes = '';
$scope.Branch_TimeFrom = '';
$scope.Branch_TimeTo = '';
$scope.Branch_Manager = '';
$scope.Branch_Phone = '';
$scope.saturday = '';
};
//get single record by ID
$scope.getForUpdate = function (Branch) {
debugger
$scope.Branch_ID = Branch.Branch_ID;
$scope.Branch_Name = Branch.Branch_Name;
$scope.Branch_Address = Branch.Branch_Address;
$scope.Branch_email = Branch.Branch_email;
$scope.Branch_Notes = Branch.Branch_Notes;
$scope.Branch_TimeFrom = moment(Branch.Branch_TimeFrom).format('hh:mm:ss a');
$scope.Branch_TimeTo = moment(Branch.Branch_TimeTo).format('hh:mm:ss a');
$scope.Branch_Manager = Branch.Branch_Manager;
$scope.Branch_Phone = Branch.Branch_Phone;
$scope.saturday = Branch.saturday;
};
//update Branch data
$scope.update = function () {
var Branch = {
Branch_ID: $scope.Branch_ID,
Branch_Name: $scope.Branch_Name,
Branch_Address: $scope.Branch_Address,
Branch_email: $scope.Branch_email,
Branch_Notes: $scope.Branch_Notes,
Branch_TimeFrom: $scope.Branch_TimeFrom,
Branch_TimeTo: $scope.Branch_TimeTo,
Branch_Manager: $scope.Branch_Manager,
Branch_Phone: $scope.Branch_Phone,
saturday : $scope.saturday
};
var updaterecords = myService.update(Branch);
updaterecords.then(function (response) {
if (response.data.success === true) {
getAllBranches();
alert("Branch updated successfully");
$scope.resetUpdate();
}
else {
alert("Branch not updated.");
}
},
function () {
alert("Error occured while updating Branch record");
});
};
//reset controls after update
$scope.resetUpdate = function () {
$scope.Branch_Name = '';
$scope.Branch_Address = '';
$scope.Branch_email = '';
$scope.Branch_Notes = '';
$scope.Branch_TimeFrom = '';
$scope.Branch_TimeTo = '';
$scope.Branch_Manager = '';
$scope.Branch_Phone = '';
$scope.saturday = '';
};
};
Index.cshtml
<div class="container" ng-controller="branchcontroller">
<table class="table table-bordered">
<thead style="background-color:lightblue;">
<tr>
<th>Branch Address</th>
<th>Branch Email</th>
<th>Branch Name</th>
<th>Branch Notes</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="branche in Branches">
<td>{{branche.Branch_Address}}</td>
<td>{{branche.Branch_email}}</td>
<td>{{branche.Branch_Name}}</td>
<td>{{branche.Branch_Notes}}</td>
<td style="width:200px;">
<a href="#"
class="btn btn-info"
data-toggle="modal"
data-target="#Update"
ng-click="getForUpdate(branche)">
Update
</a>
<a href="#" class="btn btn-danger"
id="btnDelete"
data-toggle="modal"
data-target="#deleteDialog"
ng-click="getForDelete(branche)">
Delete
</a>
</td>
</tr>
</tbody>
</table>
#*Upadate Branch records*#
<div class="modal" id="Update" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Update Existing Branch</h3>
</div>
<div class="modal-body" style="margin-left:20px">
#*Update Employee form starts here...*#
<form class="form-horizontal" name="UpdateBranchForm">
<div class="form-group">
<input class="form-control" readonly="readonly" name="Branch_ID" ng-model="Branch_ID" type="hidden" placeholder="Branch ID" />
</div>
<div class="form-group">
<label class="control-label"> Branch Address</label>
<input class="form-control" name="Branch_Address" ng-model="Branch_Address" type="text" placeholder="Branch Address" />
</div>
<div class="form-group">
<label class="control-label"> Branch email</label>
<input class="form-control" name="Branch_email" ng-model="Branch_email" type="email" placeholder="Branch email" />
</div>
<div class="form-group">
<label class="control-label"> Branch Name</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Name" type="text" placeholder="Branch Name" />
</div>
<div class="form-group">
<label class="control-label"> Branch Manager</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Manager" type="text" placeholder=" Branch Manager" />
</div>
<div class="form-group">
<label class="control-label"> Branch Phone</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Phone" type="text" placeholder="Branch Phone" />
</div>
<div class="form-group">
<label class="control-label"> Branch Notes</label>
<textarea class="form-control" name="Branch_Notes" ng-model="Branch_Notes" placeholder="Branch Notes"></textarea>
</div>
<div class="form-group">
<label class="control-label"> Time From</label>
<input ng-model="Branch_TimeFrom" type="time" name="Branch_TimeFrom" placeholder="HH:mm">
</div>
<div class="form-group">
<label class="control-label"> Time To</label>
<input ng-model="Branch_TimeTo" type="time" name="Branch_TimeTo" placeholder="HH:mm">
</div>
<div class="form-group">
<label class="control-label"> saturday</label>
<input ng-model="saturday" type="checkbox" name="saturday" placeholder="saturday">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnUpdate" data-dismiss="modal" ng-click="update()">
Update
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
here i want to get time from database then display it in input type
time
here is the time that i get it from database then i want it to
display to input type time
The AngularJS framework needs to bind JavaScript Date objects:
$http.get(url).then(response) {
var data = response.data;
data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
data.Branch_TimeTo = new Date(data.Branch_TimeTo);
$scope.data = data;
});
<label class="control-label"> Branch Notes</label>
<textarea ng-model="data.Branch_Notes">
</textarea>
<label class="control-label"> Time From</label>
<input ng-model="data.Branch_TimeFrom" type="time">
<label class="control-label"> Time To</label>
<input ng-model="data.Branch_TimeTo" type="time">
From the Docs:
The model must always be a Date object, otherwise AngularJS will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.
For more information, see
AngularJS <input type="time"> Directive API Reference
I'm new to MVC, and I'm writing my first App in this technology.
i'm trying to return an Object to my view from the controller, but I can't see it in the view, hear is my Controller code:
`
public ActionResult Create(int id)
{
AddAffiliatModel serverUsersModel = new AddAffiliatModel();
ObjectResult<getServerUsers_Result> serverUsers = serverUsersModel.getSUsers();
List<getServerUsers_Result> users = serverUsers.ToList();
return View(users[0]);
}`
And here is my View code:
#model MVC_5_Skeleton1.Models.getServerUsers_Result
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>getUsers</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="~/JS/AddAffiliate.js"></script>
<style>
.txtW {
max-width: 300px;
}
.txtAH {
height: 200PX;
}
</style>
<script type="text/javascript">
//**************************************************************************
//** Jquery Ready function hooks the buttons click events *
//**************************************************************************
$(document).ready(function () {
$(document).on('click', 'button', function (e) {
buttonId = $(this).attr("id");
switch (buttonId) {
case "submit":
Validate();
clearFields();
break;
case "cancel":
break;
default:
break;
}
});
});
//**************************************************************************
//** Validate and send *
//**************************************************************************
function SendToServer() {
}
//**************************************************************************
//** Validate and send *
//**************************************************************************
function Validate() {
var errorMsg = "";
var postString = "";
var valid = 0;
var filter = /^([a-zA-Z0-9_\.\-])+\##(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if ($('#fullName').val().length > 2) {
var name = $('#fullName').val();
}
else {
errorMsg = 'Please enter name';
valid = 1;
}
if ($('#email').val().length > 5) {
var email = $('#email').val();
}
else {
errorMsg += 'Please valid email' + '/n';
valid = 1;
}
if ($('#skype').val().length > 3) {
var name = $('#skype').val();
}
else {
errorMsg = 'Please Skype name' + '/n';
valid = 1;
}
if ($('#Countries-leagues').val().length > 5) {
var cl = $('#Countries-leagues').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if ($('#opinion').val().length > 5) {
var opinion = $('#opinion').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if (valid == 0) {
send();
}
}
//**************************************************************************
//** Get desired length and string to chech *
//**************************************************************************
function Send() {
AffiliateData.pType = 'AddAffiliate';
AffiliateData.user[0].recomanderId = "1"
AffiliateData.user[0].userName = $('#fullName').val();
AffiliateData.user[0].email = $('#email').val();
AffiliateData.user[0].skype = $('#skype').val();
AffiliateData.user[0].covered = $('#Countries-leagues').val();
AffiliateData.user[0].opinion = $('#opinion').val();
if ($('#canConnect').is(":checked")) {
AffiliateData.user[0].canContact = "1";
}
else {
AffiliateData.user[0].canContact = "0";
}
if ($('#aware').is(":checked")) {
AffiliateData.user[0].aware = "1";
}
else {
AffiliateData.user[0].aware = "0";
}
$.ajax({
type: "POST",
processData: false,
url: "http://localhost/MVC%205%20Skeleton1/AddAffilate/Create/1",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ json: AffiliateData }),
// dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
//**************************************************************************
//** Clean UI Fields *
//**************************************************************************
function clearFields() {
$('#fullName').val("");
$('#email').val("");
$('#skype').val("");
$('#email').val("");
$('#Countries-leagues').val("");
$('#opinion').val("");
$('input:checkbox').removeAttr('checked');
}
//********************* end of script block *********************
</script>
</head>
<body>
<h2>Create new Affilate</h2>
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="textinput">Candidate Name </label>
</div>
<div class="col-md-12">
<input id="fullName" name="textinput" type="text" placeholder="Candidate Name " class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="email">Email</label>
</div>
<div class="col-md-12">
<input id="email" name="email" type="email" placeholder="Email" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="skype">Skype</label>
</div>
<div class="col-md-12">
<input id="skype" name="skype" type="text" placeholder="Skype" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="Countries-leagues">Countries/leagues</label>
<div class="col-md-12">
<textarea class="form-control txtW txtAH" id="Countries-leagues" name="Countries-leagues" required=""></textarea>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="opinion">Way are you recommending Him/Her</label>
<div class="col-md-4">
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required=""></textarea>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="form-group">
<label class="col-md-12 control-label" for="checkboxes"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input type="checkbox" name="checkboxes" id="canConnect" value="0">
Can we contact he/she?
</label>
</div>
<div class="checkbox">
<label for="checkboxes-1">
<input type="checkbox" name="checkboxes" id="aware" value="0">
Dose he/she knows will approach them?
</label>
</div>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-12 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-success">Submit</button>
<button id="cancel" name="cancel" class="btn btn-primary">Cancel</button>
</div>
</div>
</fieldset>
</body>
</html>
How can I get to my #model ?
Can I use the data in my Jquery code?
Thanks
You can access your model properties by using #Model.PropertyName.
Example:
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required="">#Model.opinion</textarea>
Edited: I saw on your question commens on how to access that information with jQuery.
If you follow the previous example, you can access it by simply
$("#opinion").val()
I'm using bootstrap in my application.
I'm creating tabs, dropdown and textbox controls dynamically based on a count and applying validation to those controls.But it is validation all the controls. I need validation for visible controls , it should validate hidden controls.
Here is my code:
CategoryClass.cs
public class CategoryClass
{
public int ddlCount{ get; set; }
public int txtCount{ get; set; }
public int Id{ get; set; }
public string Name{ get; set; }
}
Default.aspx.cs
public partial class DefaultClass
{
public int CategoryCount{ get; set; }
public List<CategoryClass> CategoryList;
protected void Page_Load(object sender, EventArgs e)
{
CategoryList=new DefaultManager().GetCategoryList();
}
}
Default.aspx
<div class="row-fluid">
<div class="tabbable tabs-left">
<div id="rsc-fuelux-wizard" class="span3" style="border: 1px solid #C5D0DC; margin-right: 5px;">
<table>
<tr>
<td>
<div class="infobox infobox-light-brown infobox-dark span12" style="background-color: #B3BCC4;">
<h5 class="span12 center">
Category List</h5>
</div>
</td>
</tr>
<tr>
<td>
<ul class="nav nav-pills nav-stacked" id="CategoryTabs" style="margin-left: 5px;
margin-right: 5px;">
<%
int counter = 0;
foreach (CategoryClass Category in CategoryList)
{
counter++;
%><li stepval="<%=counter %>" id="Categoryli_<%=counter %>" <%
if (counter == 1)
{%> class="complete active" <%}
else
{%> class="complete" <%
}
%> cat-id="<%=Category.Id%>"><a href="javascript:void(0);" data-toggle="pill" onclick="ShowDiv(<%=Category.Id%>,<%=counter %>);">
<%=counter %>. <%=Category.Name%></a></li>
<%}
%>
</ul>
</td>
</tr>
</table>
<div class="tab-content">
<%counter = 0;
foreach (CategoryClass Category in CategoryList)
{
<div visibility="cat-list" id="Div_<%=Category.Id%>" style="height: 380px;"
class=" <%
if (counter == 1)
{%>tab-pane active <%
}
else
{%>tab-pane<%
}
%>">
<div class="form-horizontal">
<%if (Category.ddlCount> 0)
{
for(int i=0;i<Category.ddlCount;i++)
{%>
<div class="control-group">
<label class="control-label">DropDown <%=i++%>
</label>
<div class="controls">
<select data-val="true" data-val-required="Field is required" name="">
<option value="">--Select--</option>
<option value=1>Value1</option>
<option value=2>Value2</option>
</select>
</div>
</div>
<%
}
}
if (Category.txtCount> 0)
{
for(int i=0;i<Category.txtCount;i++)
{%>
<div class="control-group">
<label class="control-label">Textbox<%=i++%>
</label>
<div class="controls">
<input type="text" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
</div>
</div>
<%}
}%>
</div>
</div>
</div>
</div>
<button id="btnSubmit" class="btn btn-success" onclick="Submit();">
Submit</button>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
} else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
} else {
error.insertAfter(element);
}
};
}
function Submit() {
if (!$('#Form1').valid()) {
return false;
}
}
function ShowDiv(objCatId, objCounter) {
$('ul.CategoryTabs li').attr('class', 'complete');
$('#Categoryli_' + objCounter).attr('class', 'complete active');
$('div[visibility="cat-list"]').css('display', 'none');
$('#Div_' + objCatId).css('display', 'block');
}
</script>
I'm using js/jquery.validate.min.js , js/uncompressed/jquery.validate.js and js/uncompressed/jquery.validate.unobtrusive.js .
Validation should be applied for visible controls alone.
Please help me out.
Basically you have to just call ASP.NET inbuilt JS function " ValidatorEnable" after the disable method call
Enable/disable asp.net validator controls within a specific "ValidationGroup" with jQuery?
http://geekswithblogs.net/jonasb/archive/2006/08/11/87708.aspx
Disable Validation on Hidden Controls