How to validate selected controls - c#

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>

Related

how to get the value of a radio button in blazor?

hello community I have a problem how can I get the value of a radio button in blazor, I have three radio buttons in the first two I want to put a value number 0 and 16 to save them in the database and in the third button a bool value to show some input if that value was selected,but the truth is I don't know how to do this since I understand that in blazor you can't even put the bidirectional values with bind-value
this is my code:
<div class="form-group col-md-2">
<label>Impuestos</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" #bind-value="#ImpuestoDetalle.Tasa">
<label class="form-check-label" for="inlineRadio1">0%</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" #bind-value="#ImpuestoDetalle.Tasa">
<label class="form-check-label" for="inlineRadio2">16%</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" #bind="#Perzonalizado">
<label class="form-check-label" for="inlineRadio3">Perzonalizado</label>
</div>
</div>
</div>
#if (Perzonalizado)
{
<div class="form-group col-md-2">
<label>Tasa</label>
<div>
<input type="number" class="form-control" #bind-value="#ImpuestoDetalle.Tasa" />
</div>
</div>
}
#code {
private Impuesto Impuesto = new Impuesto();
private ImpuestoDetalle ImpuestoDetalle = new ImpuestoDetalle();
private Boolean Perzonalizado = false;
}
Tried this really quickly and achieved in a slightly different way using onchange event:
<div class="form-group col-md-2">
<label>Impuestos</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" #onchange="#(() => UpdatePercentage(0))">
<label class="form-check-label" for="inlineRadio1">0%</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" #onchange="#(() => UpdatePercentage(16))">
<label class="form-check-label" for="inlineRadio2">16%</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" #onchange="#(() => Perzonalized())">
<label class="form-check-label" for="inlineRadio3">Perzonalizado</label>
</div>
</div>
</div>
#if (Perzonalizado)
{
<div class="form-group col-md-2">
<label>Tasa</label>
<div>
<input type="number" class="form-control" #bind-value="#ImpuestoDetalleM.Tasa" />
</div>
</div>
}
#code {
public ImpuestoDetalle ImpuestoDetalleM = new ImpuestoDetalle();
private Boolean Perzonalizado = false;
public class ImpuestoDetalle
{
public int Tasa { get; set; }
}
public void Perzonalized()
{
Perzonalizado = true;
}
public void UpdatePercentage(int percentage)
{
Perzonalizado = false;
ImpuestoDetalleM.Tasa = percentage;
}
}
So basically when the radio button is clicked, we fill the value by passing from parameter.
You can also try the snippet here: https://blazorrepl.com/repl/ckOBGDvj26S1LtXe41

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>
}

Dropdownlist does not appear when append duplicate div in MVC

I have a div of Spouse Information. When clicking on add button I append duplicate div below the first. But the Dorpdownlist for HomeDistrict does not appear in the append div though level and other input tag works fine.
I have added the div that I appended. Everything works fine except dropdownlist.
<div class=" card-body">
<button class="btn-success text-right addspousBtn"><i class="icon icon-plus-square"> </i>Add New Spous</button>
<div class="form-row mt-1 SpousDiv">
<div class="col-6">
<div class="form-group col-12 m-0">
<label for="Username" class="col-form-label s-12"><i class="icon-user mr-2"></i>Name</label>
<input placeholder="Enter Name" class="form-control r-0 light s-12 SpousName" type="text" required>
</div>
<div class="form-group col-12 m-0">
<label for="District" class="col-form-label s-12"><i class="icon-address-card mr-2"></i>Home District</label>
<select class="custom-select select2 select2-hidden-accessible HomeDistrict" required="" tabindex="-1" aria-hidden="true">
<option value="">-Select Home District-</option>
#foreach (var item in ViewBag.Districts)
{
<option value="#item.DistrictId">#item.DistrictName</option>
}
</select>
</div>
</div>
</div>
</div>
<script>
var $remove = $('<input type="button" value="Remove" class="remove btn btn-danger" />');
$(".addspousBtn").click(function (e) {
e.preventDefault();
debugger;
var html = '<hr/><div class="form-row mt-1 SpousDiv"> <div class="col-6"> <div class="form-group col-12 m-0"> <label for="Username" class="col-form-label s-12"><i class="icon-user mr-2"></i>Name</label> <input placeholder="Enter Name" class="form-control r-0 light s-12 SpousName" type="text" required> </div><div class="form-group col-12 m-0"> <label for="RoleId" class="col-form-label s-12"><i class="icon-address-card mr-2"></i>Home District</label><select class="custom-select select2 select2-hidden-accessible HomeDistrict" required="" tabindex="-1" aria-hidden="true"><option value="">-Select Home District-</option>#foreach (var item in ViewBag.Districts){<option value="#item.DistrictId">#item.DistrictName</option>}</select></div></div></div>';
var $lastDiv = $(".card-body").find(".SpousDiv").last();
$(html).insertAfter($lastDiv);
})
</script>
and the js code to append new div
You can use
#Html.DropDownList("Districts", null, "-Select Home District-", new {#class="custom-select select2 select2-hidden-accessible HomeDistrict" })
and you must add $(".select2").select2(); to click js for the new appended element
<div class=" card-body">
<button class="btn-success text-right addspousBtn">
<i class="icon icon-plus-square"> </i>
Add New Spous
</button>
<div class="form-row mt-1 SpousDiv">
<div class="col-6">
<div class="form-group col-12 m-0">
<label for="Username" class="col-form-label s-12">
<i class="icon-user mr-2"></i>
Name
</label>
<input placeholder="Enter Name" class="form-control r-0 light s-12 SpousName" type="text" required>
</div>
<div class="form-group col-12 m-0">
<label for="District" class="col-form-label s-12">
<i class="icon-address-card mr-2"></i>
Home District
</label>
#Html.DropDownList("Districts", null, "-Select Home District-", new {#class="custom-select select2 select2-hidden-accessible HomeDistrict"
})
</div>
</div>
</div>
</div>
<script>
var $remove = $('<input type="button" value="Remove" class="remove btn btn-danger" />');
$(".addspousBtn").click(function(e) {
e.preventDefault();
debugger;
var html = '<hr/><div class="form-row mt-1 SpousDiv"> <div class="col-6"> <div class="form-group col-12 m-0"> <label for="Username" class="col-form-label s-12"><i class="icon-user mr-2"></i>Name</label> <input placeholder="Enter Name" class="form-control r-0 light s-12 SpousName" type="text" required> </div><div class="form-group col-12 m-0"> <label for="RoleId" class="col-form-label s-12"><i class="icon-address-card mr-2"></i>Home District</label>#Html.DropDownList("Districts", null, "-Select Home District-", new {#class="custom-select select2 select2-hidden-accessible HomeDistrict" })</div></div></div>';
var $lastDiv = $(".card-body").find(".SpousDiv").last();
$(html).insertAfter($lastDiv);
$(".select2").select2();
})
</script>
It seems to be an issue with the ViewBag.Districts, cast it back to what ever type you passed it as.
#{
var dis = ViewBag.Districts as List<string>; // or what ever type
// Also it can be this way...
// var dis = (List<string>)ViewBag.Districts;
}
#foreach (var item in dis)
{
<option value="#item.DistrictId">#item.DistrictName</option>
}

How to pass variable json string into application or session variable using c#?

<form>
<div class="container">
<div class="row">
<div class="col-xs-3 col-lg-2">
SELECT bank name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
father name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
<div class="col-xs-3 col-lg-2">
father pan no
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
mother name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
<div class="col-xs-3 col-lg-2">
mother pan no
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
Account numbers
</div>
<div class="col-xs-3 col-md-6 col-lg-6">
<textarea class="form-control" rows="5" id="fno"></textarea>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<input type="button" runat="server" value="Generate Ffile" id="file" onclick="submit_file_Click();" />
</div>
</div>
</form>
var accountNum;
var bank_name;
var bank;
var fn;
var fpan;
var mn;
var mpan;
var jsonObj = [];
var customerString;
var accString;
$(document).ready(function() {
$("#file").on("click", function() {
customerdetails(amc_name);
accountDetails();
});
});
function customerdetails(amc_name) {
jsonObj = [];
bank = bank_name;
fn = $("#fname").val();;
fpan = $("#pan1").val();;
mn = $("#mname").val();;
mpan = $("#mpan2").val();;
item = {}
item["BANKName"] = bank;
item["F_Name"] = fn;
item["F_PAN"] = fpan;
item["M_Name"] = mn;
item["M_PAN"] = mpan;
jsonObj.push(item);
customerString = JSON.stringify(jsonObj);
}
function accountDetails() {
jsonObj = [];
accountNum = $('textarea#fno').val();
item = {}
item["ACNum"] = accountNum;
jsonObj.push(item);
accString = JSON.stringify(jsonObj);
}
when user enter details onto html form than I used jQuery to get JSON String of customer details and account details .Now I want to store these JSON string into application or session variable where customer details will store into one session variable and account details will store into another session variable.
I am using but is not working
No, you can not do this because serverside code executes before the javascript. You can do this by using hiddenfield, set hiddenfield value from jquery and get that from your serverside.

HTTP Post 400 (Bad Request) After DropDownList

My program is basically for technicians to key in their service report after they've fixed a computer.
I have one feature that allows them to create a new report and a part of the report is keying in the customer's name or in other words, the company's name.
I was first struggling to make a dropdownlist so that the technicians get easily pick the name of a customer that is already in the server. I gave up for a while and decided to put a normal
<input type="text"/>
and when I did a post method, everything worked fine.
However, after having succeeded at making a dropdownlist for the customers' names, I could not do a POST method any more due to a POST 400 (Bad Request). I checked the developer tools and noticed that instead of the name of the customer, it just inserted 'Object'.
My question is, will someone please point me in the right direction? I've been scratching my head the whole morning and I just can't figure out why.
CreateReport.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts {
#Scripts.Render("~/bundles/app")
}
<div class="page-header">
<h1>Add New Report</h1>
</div>
<br>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Create New Report</h2>
</div>
<div class="panel-body">
<form class="form-horizontal" data-bind="submit: addReport">
<div class="form-group">
<label for="inputCustName" class="col-sm-2 control-label">Customer's Name</label>
<div class="col-sm-12">
<select data-bind="options:customers, optionsText: 'Name', value: newReport.CustomerName"></select>
<span data-bind="value"
</div>
</div>
<div class="form-group" data-bind="with: newReport">
<label for="inputRepId" class="col-sm-2 control-label">Report Id</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputRepId" data-bind="value:Id" />
</div>
<br>
<label for="inputDate" class="col-sm-2 control-label">Date</label>
<div class="col-sm-12">
<input type="date" class="form-control" id="inputDate" data-bind="value:Date" />
</div>
<br>
<label for="inputWarranty" class="col-sm-2 control-label">Warranty</label>
<div class="col-sm-12">
<input type="radio" name="Warranty" value="true" data-bind="checked:Warranty">Yes
<br>
<input type="radio" name="Warranty" value="false" data-bind="checked: Warranty">No
</div>
<br>
<label for="inputNature" class="col-sm-2 control-label">Nature of Service</label>
<div class="col-sm-12">
<input type="radio" name="ServiceNature" value="Installation" data-bind="checked:ServiceNature">Installation <input type="radio" name="ServiceNature" value="Repair" data-bind="checked:ServiceNature">Repair
<br>
<input type="radio" name="ServiceNature" value="Terminate" data-bind="checked:ServiceNature">Terminate <input type="radio" name="ServiceNature" value="Maintenance" data-bind="checked:ServiceNature">Maintenance
</div>
<br>
<label for="inputLabCost" class="col-sm-2 control-label">labour Charge</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputLabCost" data-bind="value:LabourCharge" />
</div>
<br>
<label for="inputMatCost" class="col-sm-2 control-label">Material Cost</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputMatCost" data-bind="value:TotalMaterial" />
</div>
<br>
<label for="inputTransport" class="col-sm-2 control-label">Transport</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputTransport" data-bind="value:Transport" />
</div>
<br>
<label for="inputTotal" class="col-sm-2 control-label">Total</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputTotal" data-bind="value:Total" />
</div>
<br>
<label for="inputComments" class="col-sm-2 control-label">Comments</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputComments" data-bind="value:Comments" />
</div>
<br>
<label for="inputCusId" class="col-sm-2 control-label">Customer's ID</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputCusId" data-bind="value:CustomerId" />
</div>
<br>
<label for="inputEngId" class="col-sm-2 control-label">Engineer's ID</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputEngId" data-bind="value:UserId" />
</div>
<br>
<!--
<script>
function myFunction() {
var y = document.getElementById("inputMatCost").value;
var z = document.getElementById("inputTransport").value;
var x = +y + +z;
document.getElementById("inputTotal").value = x;
}
</script>
-->
<!-- <select id="CustomerDropDown"></select> -->
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<!-- This is using bootstrap modal component. This replace the simple native javascript alert as Selenium (Assignment 2) has problem detecting native javascript alert and therefore unable to do recording correctly
It is a bit longer but it also looks more presentatble as you can further style it if you like-->
<<div class="modal fade" tabindex="-1" role="dialog" id="reportAlert">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>New Report Has Been Successfully Added!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Back To Reports</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
app.js(script that the view is connected to)
var ViewModel = function () {
var self = this;
self.reports = ko.observableArray();
self.customers = ko.observableArray();
self.error = ko.observable();
self.detail = ko.observable();
self.newReport = {
Id: ko.observable(),
CustomerName: ko.observable(),
Date: ko.observable(),
Warranty: ko.observable(),
ServiceNature: ko.observable(),
LabourCharge: ko.observable(),
TotalMaterial: ko.observable(),
Transport: ko.observable(),
Total: ko.observable(),
Comments: ko.observable(),
CustomerId: ko.observable(),
UserId: ko.observable()
}
var reportsUri = 'http://localhost:64744/api/report/';
var customersUri = 'http://localhost:64744/api/customer/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllReports() {
ajaxHelper(reportsUri, 'GET').done(function (data) {
self.reports(data);
});
}
function getCustomers() {
ajaxHelper(customersUri, 'GET').done(function (data) {
self.customers(data);
});
}
self.getReportDetail = function (item) {
ajaxHelper(reportsUri + item.Id, 'GET').done(function (data) {
self.detail(data);
});
}
//GET method, addReport
self.addReport = function (formElement) {
var report = {
Id: self.newReport.Id(),
CustomerName: self.newReport.CustomerName(),
Date: self.newReport.Date(),
Warranty: self.newReport.Warranty(),
ServiceNature: self.newReport.ServiceNature(),
LabourCharge: self.newReport.LabourCharge(),
TotalMaterial: self.newReport.TotalMaterial(),
Transport: self.newReport.Transport(),
Total: self.newReport.Total(),
Comments: self.newReport.Comments(),
CustomerId: self.newReport.CustomerId(),
UserId: self.newReport.UserId()
};
ajaxHelper(reportsUri, 'POST', report).done(function (item) {
self.reports.push(item);
$('#reportAlert').modal('show');
});
}
$('#reportAlert').on('hidden.bs.modal', function (e) {
window.location = "ReportInfo";
})
//DELETE METHOD deleteReportMethod
self.deleteReport = function (item) {
ajaxHelper(reportsUri + item.Id, 'DELETE').done(function (data) {
//just to inform the user that delete has been performed
$('#deleteRepAlert').modal('show');
});
}
// jquery event to detect when the user dismiss the modal.... to redirect back to the home page
$('#deleteRepAlert').on('hidden.bs.modal', function (e) {
window.location = "ReportInfo";
})
// Fetch the initial data.
getAllReports();
getCustomers();
};
ko.applyBindings(new ViewModel());
You are not telling Knockout what property holds the value to be stored in the options binding. I am guessing that the customers array holds complex objects. So you need to tell Knockout which property on those objects holds the value. If you want to store the Name property as the value as well:
<select data-bind="options:customers, optionsText: 'Name', optionsValue: 'Name', value: newReport.CustomerName"></select>
HTTP status 400 indicates that your parameter is wrong. Maybe parameter type or parameter name

Categories

Resources