How to get the checkbox values on windows load event using jquery - c#

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>

Related

How to trigger Model Validation inside modal? .NET 5

i Have problem when i try the model validation by trying to fill the form by false.
And when i try to submit with the wrong value (not valid by model validator) it redirects to the page (without model).
Here's the screenshot :
Customer Index
redirect to Customer Create Page when i submit
Here's the code
CONTROLLER
//POST CREATE
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Models.Customer obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//GET DELETE
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var obj = _db.Customers.Find(id);
if (obj == null)
{
return NotFound();
}
return PartialView(obj);
}
Model
public class Customer
{
[Key]
public int Id { get; set; }
[DisplayName("Nama Customer")]
[Required]
[MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
public string Nama { get; set; }
public string Alamat { get; set; }
[Phone]
[Required]
public string Telp { get; set; }
}
Index.HTML Button Create
<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>
JS
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
CREATE CSHTML
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-4">
<h2 class="text-black-50 pl-3">Add Customer</h2>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
#*validasi form*#
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-6">
</div>
<div class="col-6">
</div>
<div class="col-6">
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you (:
And when i try to submit with the wrong value (not valid by model
validator) it redirects to the page (without model).
You use return View(obj); when modelstate is not valid. So it will return view with model and the view name should be the action name(Create) if you do not specific view name. So this result is correct by using your code.
Here is a working demo:
Index.cshtml:
<button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
<div class="modal fade" id="modalCustomer" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
//$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
</script>
}
Create.cshtml:
#model Customer
#{
Layout = null; //be sure add this...
}
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
#*change here..........*#
<input type="button" id="btn" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
JS in Create.cshtml:
<script>
$(document).on('click', '#modalCustomer #btn', function () {
var options = {};
options.type = "POST";
options.url = "/Customer/create";
options.dataType = "JSON";
options.cache = false;
options.async = true;
options.data = $("form").serialize();
options.success = function (data) {
//do your stuff...
$('#modalCustomer').modal('hide');
//if you don't want to stay in Index
//add the following code..
// window.location.href = "/home/privacy";
};
options.error = function (res) {
$('#modalBody').html(res.responseText);
};
$.ajax(options);
});
</script>
Update:
If modelstate is invalid, it will get into options.error and display the error message in modal. If modelstate is valid, it will get into options.success, you could redirect by using window.location.href or hide the modal by $('#modalCustomer').modal('hide');, just do your stuff.
Backend code should be like below:
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Customers obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return Json(new { success = true }); //change this...
}
return View(obj);
}

PartialView not returning bound model properties

I have a controller I am calling through jQuery AJAX. It takes the data in my page and returns a partial view. The purpose of the view is to pre-fill some Input fields with data which I am pulling from a data source.
The problem is, that when the partial view gets rendered in the browser, the form field input values do not get populated with the values I have added to the viewmodel.
I can put a breakpoint on the Return line and see that vm is correctly populated with my properties as I would want them.
But when I view the response in the network tab of Chrome Developer Tools the values are empty.
Anyone with any ideas why?
Controller
[HttpPost]
public async Task<IActionResult> ViewEditRaceOption(RaceViewModel race)
{
var vm = race;
var option = race.RaceOptionData.FirstOrDefault(o => o.Number == race.EditOption);
vm.OptionAffiliatedDiscountValue = option.AffiliatedDiscountValue;
vm.OptionColour = option.OptionColour;
vm.OptionEmbedMapURL = option.EmbedMapURL;
vm.OptionEntryPremium = option.Premium;
vm.OptionEntryPrice= option.AffiliatedDiscountValue;
vm.OptionMaxEntries= option.MaxEntries;
vm.OptionName= option.Name;
vm.OptionRaceDistance = option.RaceDistance;
vm.OptionStartTime = option.StartTime;
vm.OptionCertificateFileName = option.CourseMeasurementCertificateFileName;
return PartialView("OptionModal", vm);
}
Main View (Contains the Ajax JS), truncated
#using TechsportiseOnline.Helpers
#model TechsportiseOnline.ViewModels.RaceViewModel
#{
ViewData["Title"] = "Race";
}
<script>
$(function () {
$("#racedatepicker").datepicker({
dateFormat: "d MM yy",
changeMonth: true,
changeYear: true
});
});
</script>
#if (Model.FormAction == "Create")
{
<h2>Create a new race</h2>
}
else
{
<h2>#Model.RaceData.Name | <span class="text-muted">Edit Race</span></h2>
<h4>#Model.RaceData.RaceDate.ToString("dd MMMM yyyy")</h4>
}
<form asp-action="#Model.FormAction" enctype="multipart/form-data" id="race">
<input type="hidden" name="FormAction" value="#Model.FormAction" />
<input id="DeleteOption" name="DeleteOption" type="hidden" value="0" />
<input id="EditOption" name="EditOption" type="hidden" value="0" />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="optionsmodal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h2 class="modal-title">Race Option</h2>
<input type="hidden" name="NewOption" value="false" id="NewOption" />
</div>
<div class="modal-body">
#{Html.RenderPartial("_StatusMessage", Model.Message);}
<div id="optionmodal">
#{Html.RenderPartial("OptionModal", Model);}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default cancelmodal">Cancel</button>
<button type="button" class="btn btn-primary" id="addoption">Add</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Race Details</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label asp-for="RaceData.Name" class="control-label"></label>
<br /><small class="text-muted">The name or title of your race</small>
<input asp-for="RaceData.Name" class="form-control" />
<span asp-validation-for="RaceData.Name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label asp-for="RaceData.ContactName" class="control-label"></label>
<br /><small class="text-muted">The name of the Race Director whom people should contact with queries</small>
<input asp-for="RaceData.ContactName" class="form-control" />
<span asp-validation-for="RaceData.ContactName" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="RaceData.ContactEmail" class="control-label"></label>
<br /><small class="text-muted">The email address of the Race Director whom people should contact with queries</small>
<input asp-for="RaceData.ContactEmail" class="form-control" />
<span asp-validation-for="RaceData.ContactEmail" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="RaceData.ContactNumber" class="control-label"></label>
<br /><small class="text-muted">The phone number of the Race Director whom people should contact with queries</small>
<input asp-for="RaceData.ContactNumber" class="form-control" />
<span asp-validation-for="RaceData.ContactNumber" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="RaceData.RaceDate" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="icon-calendar"></i> </span>
<input name="RaceData.RaceDate" value="#Model.RaceData.RaceDate.ToString("dd MMMM yyyy")" type="text" class="form-control" id="racedatepicker" autocomplete="off">
</div>
<span asp-validation-for="RaceData.RaceDate" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="RaceData.Description" class="control-label"></label>
<br /><small class="text-muted">As much description as you want to add for your race to give your participants as much as they need to know</small>
<textarea asp-for="RaceData.Description" class="form-control" rows="10" id="description">#Model.RaceData.Description</textarea>
<span asp-validation-for="RaceData.Description" class="text-danger"></span>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Race Options</div>
<div class="panel-body">
<div id="container">
Create your different Race Options here, if you want to have more than one distance/race in the same event. You must have at least 1 Race Option.
<div id="dvRaceOptionsResults">
#{Html.RenderPartial("RaceOptions", Model);}
</div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">Add Race Option</button>
</div>
</div>
</div>
</div>
TRUNCATED HERE
<div class="form-group">
#if (Model.FormAction == "Create")
{
<input type="submit" value="Create" class="btn btn-primary" />
}
else
{
<input type="submit" value="Save" class="btn btn-primary" />
}
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
</form>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).on('click', '.cancelmodal', function () {
console.log("cancel modal")
var premiumrace = document.getElementById("RaceData_Premium").value
document.getElementById("OptionName").value = ""
document.getElementById("OptionRaceDistance").value = ""
document.getElementById("OptionMaxEntries").value = 0
document.getElementById("OptionStartTime").value = "19:00"
document.getElementById("OptionEmbedMapURL").value = ""
document.getElementById("OptionColour").value = "White"
document.getElementById("OptionEmbedMapURL").value = ""
if (premiumrace == true) {
document.getElementById("OptionEntryPremium").value = false
document.getElementById("OptionEntryPrice").value = "0"
document.getElementById("OptionAffiliatedDiscountValue").value = "2.00"
}
$("#optionsmodal").modal("hide")
});
</script>
<script type="text/javascript">
$(document).on('click', '.editmodal', function () {
var optionnumber = $(this).attr('number');
document.getElementById("EditOption").value = optionnumber;
var form = document.getElementById('race');
var formData = new FormData(form);
$.ajax({
url: '#Url.Action("ViewEditRaceOption", "Races")',
type: 'POST',
data: formData,
dataType: 'html',
processData: false,
contentType: false,
success: function(response) {
if (response) { // check if data is defined
$("#optionmodal").html(response);
console.log(response);
$("#optionsmodal").modal("show");
}
}
});
document.getElementById("EditOption").value = 0;
});
</script>
<script type="text/javascript">
$(document).on('click', '.editoption', function () {
var optionnumber = $(this).attr('number');
document.getElementById("EditOption").value = optionnumber;
var form = document.getElementById('race');
var formData = new FormData(form);
$.ajax({
url: '#Url.Action("EditRaceOption", "Races")',
type: 'POST',
data: formData,
dataType: 'html',
processData: false,
contentType: false,
success: function(response) {
if (response) { // check if data is defined
$("#dvRaceOptionsResults").html(response);
}
}
});
document.getElementById("EditOption").value = 0;
});
</script>
<script type="text/javascript">
$(document).on('click', '.removeoption', function () {
var optionnumber = $(this).attr('number');
document.getElementById("DeleteOption").value = optionnumber;
$.ajax({
url: '#Url.Action("RemoveRaceOption", "Races")',
type: 'POST',
data: $("#race").serialize(),
dataType: 'html',
success: function(response) {
if (response) { // check if data is defined
$("#dvRaceOptionsResults").html(response);
}
}
});
document.getElementById("DeleteOption").value = 0;
});
</script>
<script type="text/javascript">
$("#addoption").click(function () {
document.getElementById("NewOption").value = "true";
var form = document.getElementById('race');
var formData = new FormData(form);
$.ajax({
url: '#Url.Action("AddRaceOption", "Races")',
type: 'POST',
data: formData,
dataType: 'html',
processData: false,
contentType: false,
success: function(response) {
if (response) { // check if data is defined
$("#optionsmodal").modal("hide");
$("#dvRaceOptionsResults").html(response);
document.getElementById("OptionName").value = null;
document.getElementById("OptionRaceDistance").value = "";
}
}
});
document.getElementById("NewOption").value = "false";
});
</script>
<script type="text/javascript">
tinymce.init({
selector: 'textarea',
height: 400,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor textcolor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table contextmenu paste code help'
],
toolbar: 'preview | formatselect | bold italic underline strikethrough forecolor | alignleft aligncenter alignright alignjustify | bullist numlist | image link media | removeformat ',
content_css: [
'//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
'//www.tinymce.com/css/codepen.min.css']
});
// Prevent Bootstrap dialog from blocking focusin
$(document).on('focusin', function (e) {
if ($(e.target).closest(".mce-window").length) {
e.stopImmediatePropagation();
}
});
</script>
<script type="text/javascript" src="~/js/autocomplete/jquery.easy-autocomplete.min.js"></script>
<link rel="stylesheet" href="~/js/autocomplete/easy-autocomplete.min.css">
<script type="text/javascript">
var options = {
url: "../../resources/countries.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#countries").easyAutocomplete(options);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZMX9gUpf7jFKwPe6r6dtqmrv-EnnXsU4&libraries=places&callback=initAutocomplete"
async defer></script>
<script type="text/javascript">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
administrative_area_level_1: 'short_name',
administrative_area_level_2: 'short_name',
postal_town: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'] });
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
}
Partial View
#model TechsportiseOnline.ViewModels.RaceViewModel
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label value="OptionName" class="control-label">Option Name</label>
<br /><small class="text-muted">The name of this Race Option</small>
<input asp-for="OptionName" name = "OptionName" placeholder="Your 10k" type="text" class="form-control" aria-label="Name">
<span asp-validation-for="OptionName" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label name="OptionRaceDistance" value="Race Distance" class="control-label">Distance</label>
<br /><small class="text-muted">Choose a race distance, used for Age Grading </small>
<select asp-for="OptionRaceDistance" required class="form-control">
<option value="" selected>--select--</option>
<option value="M1">1 mile</option>
<option value="KM5">5 km</option>
<option value="KM6">6 km</option>
<option value="M4">4 miles</option>
<option value="KM8">8 km</option>
<option value="M5">5 miles</option>
<option value="KM10">10 km</option>
<option value="KM12">12 km</option>
<option value="KM15">15 km</option>
<option value="M10">10 miles</option>
<option value="KM20">20 km</option>
<option value="Half">Half Marathon</option>
<option value="KM25">25 km</option>
<option value="KM30">30 km</option>
<option value="Marathon">Marathon</option>
<option value="KM50">50 km</option>
<option value="M50">50 miles</option>
<option value="KM100">100 km</option>
<option value="KM150">150 km</option>
<option value="M100">100 miles</option>
<option value="KM200">200 km</option>
<option value="Other">Other</option>
</select><br />
<span asp-validation-for="OptionRaceDistance" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label name="OptionMaxEntries" value="Maximum Entries" class="control-label">Maximum Entries</label>
<br /><small class="text-muted">The maximum capacity of the race</small>
<input asp-for="OptionMaxEntries" class="form-control" type="number" />
<span asp-validation-for="OptionMaxEntries" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label name="OptionStartTime" value="Start Time" class="control-label">Race Start Time</label>
<br /><small class="text-muted">Start time in HH:MM</small>
<input asp-for="OptionStartTime" value="19:00" asp-format="{0:hh:mm}" class="form-control" type="time" />
<span asp-validation-for="OptionStartTime" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Colour</label>
<br /><small class="text-muted">Choose the colour for this option. </small>
<select asp-for="OptionColour" class="form-control">
<option value="White" selected>White</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
<option value="Silver">Silver</option>
<option value="Orange">Orange</option>
</select><br />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Course Measurement Certificate</label>
<br /><small class="text-muted">PDF file of certificate for this race option</small>
<input asp-for="OptionCourseMeasurementCertificateFile" type="file" class="form-control" />
<span asp-validation-for="OptionCourseMeasurementCertificateFile" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Course Map URL</label>
<br /><small class="text-muted">Provide a URL to a Garmin, Strava or other course mapping tool</small>
<input asp-for="OptionEmbedMapURL" class="form-control" />
<span asp-validation-for="OptionEmbedMapURL" class="text-danger"></span>
</div>
</div>
</div>
#if (Model.RaceData.CanBePremium)
{
<div class="row">
<div class="col-md-4">
<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="OptionEntryPremium" /> Premium Race Option
<br /><small class="text-muted">This is a premium race option and will cost #Model.BaseCurrency.Symbol#Model.BaseFee.ToString("0.00") per race entry</small>
</label>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label value="OptionEntryPrice" class="control-label">Entry Price</label>
<br /><small class="text-muted">The price of the normal race entry</small>
<input asp-for="OptionEntryPrice" type="number" class="form-control" aria-label="Amount" placeholder="10.00" asp-format="{0:0.00}" >
<span asp-validation-for="OptionEntryPrice" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Affiliation Discount</label>
<br /><small class="text-muted">Value of discount for affiliation</small>
<input asp-for="OptionAffiliatedDiscountValue" type="number" class="form-control" aria-label="Amount" value="2.00" asp-format="{0:0.00}" >
<span asp-validation-for="OptionAffiliatedDiscountValue" class="text-danger"></span>
</div>
</div>
</div>
}

Can't see my Controller object in my MVC 5 View

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()

How to validate selected controls

Im using bootstrap controls in my application.
I validating my page using jquery.validate.js and jquery.validate.unobtrusive.js.
I need to validate only visible controls, but im facing issues there.
Here is my code:
<div class="form-horizontal">
<div id="BaseQuesList_4" class="base-ques-list_4">
<h4 class="blue" style="font-weight: bold;">
Sample Questionnaire</h4>
<div class="hr hr-dotted">
</div>
<div class="space-12">
</div>
<div class="control-group info" ques-id="44" ctrl-type="radio">
<label class="control-label">
1
.
Physically isolated & access controlled ODC mandated?
</label>
<div class="controls">
<label class="inline">
<input type="radio" id="rdbBaseAns_38" name="44_question" ques-id="44" value="38" ans-id="38" ans-value="Yes" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> Yes</span>
</label>
<label class="inline">
<input type="radio" id="rdbBaseAns_39" name="44_question" ques-id="44" value="39" ans-id="39" ans-value="No" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> No</span>
</label>
</div>
</div>
<div class="Question_44">
<div base-ques-id="44" id="tblDeptQuesList_45" class="rscDeptQuest38" dept-class="DeptQuesList" style="display: block;">
<div class="control-group error" rsc-ques-id="45" rsc-ctrl-type="textbox">
<label class="control-label">
<i class="icon-hand-right blue"></i>
No. Visitor Policy Defined?
</label>
<div class="controls">
<input type="text" ques-id="45" number="true" data-val-required="Field is required" data-val="true" name="name_45" id="txtDeptAnswer_45">
</div>
</div>
</div>
</div>
</div>
</div>
<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 GetQuesList(ddlAnswer) {
var QuestionId = $(ddlAnswer).attr('ques-id');
var AnswerId = $(ddlAnswer).val();
var className = "rscDeptQuest" + AnswerId;
$('div.Question_' + QuestionId + ' div[dept-class="DeptQuesList"]').css('display', 'none');
$('div.tab-content div[class="' + className + '"]').css('display', 'block');
}
</script>
I need to validate rdbBaseAns_39 control.If the option selectecd for rdbBaseAns_39 is Yes , then i need to validate txtDeptAnswer_45. but im validating all the controls all a stretch.
Please help me out.
Give the separate names name="44_question" like this name="44_question_1" for radio fields
<input type="radio" id="rdbBaseAns_38" name="44_question_1" ques-id="44" value="38" ans-id="38" ans-value="Yes" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> Yes</span>
<input type="radio" id="rdbBaseAns_39" name="44_question_2" ques-id="44" value="39" ans-id="39" ans-value="No" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> No</span>

Validation issue in textbox controls

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"/>

Categories

Resources