Populating MVC 5 View ComboBox using Javascript based on another ComboBox selection - javascript

I'm working on an ASP.NET Core MVC web project and I want to populate values of ComboBox B (Churches) based on selection of ComboBox A (Stations) using JavaScript (Json). I have tried to research with no success.
Here are my codes:
MVC View Code:
<div class="form-group">
<label asp-for="RSTATIONID" class="col-sm-4 control-label">Station:</label>
<div id="station" class="col-sm-8">
<select asp-for="RSTATIONID" class="form-control" asp-items="ViewBag.RSTATIONID"
onchange="LoadChurches(this)"></select>
<span asp-validation-for="RSTATIONID" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="RCHURCHID" class="col-sm-4 control-label">Church:</label>
<div id="church" class="col-sm-8">
<select asp-for="RCHURCHID" class="form-control" asp-items="ViewBag.RCHURCHID"></select>
<span asp-validation-for="RCHURCHID" class="text-danger" />
</div>
</div>
JavaScript Code:
function LoadChurches(e) {
var stationID = e.value;
//alert(stationID);
$.ajax
({
url: '/CaptureReceipts/LoadChurches',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stationID: +stationID
}),
success: function (result) {
var res = result.value;
alert(JSON.stringify(res));
/*$("#church").html("");
$.each($.parseJSON(result), function (i, church) {
SetSel(this);
}); */
},
error: function () {
alert("Churches can not load");
}
});
}
Controller Code:
public JsonResult LoadChurches(string statID)
{
int stationID = Convert.ToInt32(statID);
var churches = new SelectList(_context.v_Church.Where(m => m.StationID == stationID), "ID", "churchName");
return Json(ViewData);
}
The Controller name is CaptureReceiptsController. Please help me know what may be wrong.

In controller return simple json array:
var churches = _context.v_Church
.Where(m => m.StationID == stationID)
.Select(x => new {id = x.ID, name = x.churchName })
.ToArray();
return JSON(churches);
In success callback:
success: function (data) {
var churchSelect = $("#church > select")
churchSelect.html(""); //clear select
for (var i =0;i<data.length;i++){
var opt = document.createElement('option');
opt.innerHTML = data[i].name;
opt.value = data[i].id;
churchSelect.append(opt);
}
}

Related

Need to multiply values according to the switch

In my web application, I created this view. Here it has columns Item Description, Qty and again I get some data from the model and generate the other columns with the model count.
So as an example if there is 2 records in the list, design created as
Item Description, Qty, Sup 01, Sup 02
Then I load the values to that columns from the model. Also there is a switch button to check that line is approved or not. There is for Ajax code in the script to pass that ID, and the switch value to the control.
Additionally I want to add another column at the end as "Total Value". User switch the value as true I want to get that sup value and multiply with the column and need to show the amount on that column.
This is what I have tried. But it doesn't work
<div class="card-body">
<div class="row">
<div class="col-md-3 col-sm-3">
<strong>Item Description</strong>
</div>
<div class="col-md-1 col-sm-1">
<strong>Quantity</strong>
</div>
#foreach (var item in Model.ToList().First().PurchasingDetailsSup) //new columns will be created with the supplier count that user added earlier
{
<div class="col-md-2 col-sm-2">
<strong> #Suppliers.Find(x => x.Value == item.Supp_Id.ToString()).Text</strong>
</div>
}
</div>
#foreach (Asp_PASMVC.Models.PurchasingDetails item in Model)
{
<div class="row">
<div class="col-md-3">
#item.Item_Description
</div>
<div class="col-md-1">
#item.Qty
</div>
#for (int i = 0; i < item.PurchasingDetailsSup.Count; i++)
{
<div class="col-md-2">
#item.PurchasingDetailsSup[i].Unit_Amount
<input type="checkbox" value="#item.PurchasingDetailsSup[i].IsApproved" class="bootstrap-switch bwitch" data-style="ios" data-id="#item.PurchasingDetailsSup[i].Id" data-onstyle="success" data-offstyle="danger" />
</div>
}
</div>
}
</div>
<script>
$(".bootstrap-switch").change(function () {
var Checked = this.checked;
var Id = $(this).data('id');
var Qty = document.getElementById('Qty').value;
var Amount = document.getElementById('Amount').value;
IsApproved(Id, Checked);
calculate(Qty, Amount);
});
function IsApproved(id, chkValue) {
//alert(chkValue);
$.ajax({
url: '../UpdateApproveStatus',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: { Id: id, IsChecked: chkValue },
success: function (data) {
if (data.Success != true) {
console.log('Error In IsApprove');
}
}
});
function calculate(qty,amount) {
var myResult = qty * amount;
alert(myResult)
}
}
</script>
You must move the calculate function out of the IsApproved function
$(".bootstrap-switch").change(function () {
var Checked = this.checked;
var Id = $(this).data('id');
var Qty = document.getElementById('Qty').value;
var Amount = document.getElementById('Amount').value;
IsApproved(Id, Checked);
calculate(Qty, Amount);
});
function IsApproved(id, chkValue) {
//alert(chkValue);
$.ajax({
url: '../UpdateApproveStatus',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: { Id: id, IsChecked: chkValue },
success: function (data) {
if (data.Success != true) {
console.log('Error In IsApprove');
}
}
});
}
function calculate(qty, amount) {
var myResult = qty * amount;
alert(myResult)
}

Validating Javascript Autocomplete

I have a web page with two TextBoxFor fields that utilize Javascript autocomplete. With one of the fields, ClientUser, the response includes an integer and a string. The integer is then compared with another integer field on the page, ClientID, and if they match, the string is used in the autocomplete suggestions. The other field's response, WorkmateUser, is a string list immediately usable in the autocomplete.
The controller is being hit and returning the correct total list, then the correct Url/field needing validation is chosen, but the list needing validation is undefined for the ClientUser autocomplete field needing validation. What is the most efficient way to compare an integer field on the page with an integer returned for the autocomplete list? Thanks in advance!
Razor:
<div class="row">
<div class="col-lg-12">
#Html.LabelFor(m => m.WorkmateUser, "Workmate To Add", new { #class = "control-label" })
#Html.TextBoxFor(m => m.WorkmateUser, new { data_autocomplete_url = Url.Action("GetWorkmates"), #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(m => m.ClientID, "Firm To Include", "--Choose Firm--")
#Html.DropDownListFor(m => m.ClientID, StaticCache.GetClients(Model.UserID), new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(m => m.ClientUser, "Client To Add", new { #class = "control-label" })
#Html.TextBoxFor(m => m.ClientUser, new { data_autocomplete_url = Url.Action("GetAllClients"), #class = "form-control" })
</div>
</div>
Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('*[data-autocomplete-url]')
.each(function () {
var $url = $(this);
$(this).autocomplete({
source: $(this).data("autocomplete-url"),
response: function (data) {
if ($(this).data("autocomplete-url") == "/Message/GetAllClients") {
var aList = [];
for (var i = 0; i < data.length; i++) {//data.length is undefined!!!
if (data[i].ClientID == $("#ClientID").val()) {
aList.push(data[i].FirstName);
}
}
return bros;
}
else {
return data;
}
}
});
});
});
</script>
It's probably not the most elegant solution, but I ended up separating out the autocomplete call that needs validation into its own script and passing the additional variable into the controller to do validation on the back end. The following works:
Script:
<script>
$(document).on('keyup', '#ClientUser', function () {
var abID = $(this),
cID = $("#ClientID").val(),
cList = [];
$.ajax({
type: "GET",
url: '#Url.Action("GetAllClients", "Message")',
data: { term: abID.val(), clientID: cID },
success: function (data) {
for (var i = 0; i < data.length; i++) {
cList.push(data[i]);
}
},
error: function () {
alert("Client employeess could not be pulled.");
}
});
abID.autocomplete({
source: cList
});
});
</script>

Javascript Select Child With Id Formatting

Programming a ASP.net webapp to insert an entry into a database on form submit.
I've tried numerous configurations of find() and children() and they either
1) error
2) pass empty strings instead of what I type
This one errors like this:
Whats the correct way to select the individual children of myform?
Javascript (the first block here is the code I'm asking about)
var entry_array = [];
entry_array[0] = $('#myform').children('#01').css().text();
entry_array[1] = $('#myform').children('#02').css().text();
entry_array[2] = $('#myform').children('#03').css().text();
entry_array[3] = $('#myform').children('#04').css().text();
$(document).ready(function () {
$("#myform").submit(function () {
alert("Function ran");
$.ajax({
url: 'Home/SubmitEntry', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
datatype: 'json',
traditional: true,
data: { 'entry_array': entry_array },
success: function(response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
alert("Function finished running");
});
});
Controller
[HttpPost]
public ActionResult SubmitEntry(List<String> entry_array)
{
String firstname = entry_array[0];
String lastname = entry_array[1];
String town = entry_array[2];
String order = entry_array[3];
knightsEntities db = new knightsEntities();
int nextiD = 0;
nextiD = db.Apprentenceship_Sheet.ToList().Last().id + 1;
var newApprentenceship_Sheet = new Apprentenceship_Sheet();
newApprentenceship_Sheet.first_name = firstname;
newApprentenceship_Sheet.last_name = lastname;
newApprentenceship_Sheet.hailed_town = town;
newApprentenceship_Sheet.order = order;
newApprentenceship_Sheet.id = nextiD;
db.Apprentenceship_Sheet.Add(newApprentenceship_Sheet);
db.SaveChanges();
return View();
}
View
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="~/scripts/custom.js"></script>
#{
ViewBag.Title = "Home Page";
}
<div>
<form id= "myform" method="post">
First_name:<br>
<input type="text" id="01" name="firstname"><br>
Last_name:<br>
<input type="text" id="02" name="lastname"><br>
Town:<br>
<input type="text" id="03" name="town"><br>
Order:<br>
<input type="text" id="04" name="order"><br>
<br>
<input type='submit' id="05" name="Submit">
</form>
</div>
You can get the values of the text boxes directly by using $('#01').val(), or if you want refer it with reference to your form. You can use $('#myform').find('#01').val(). It will give the value of the text-box. Here is the jsfiddle for u.
$('#myform').find('#01').val()
$('#01').val()
http://jsfiddle.net/71weztcn/

AJAX send form with data and multiple image to asp.net mvc action

It has been like two days. I have been searching on the web, but I cant figure out the solution.
I have some input fields, where I can Insert text and select images. They are variable, that means if you want more fields to add more products you can click on "+" and I add another field set.
When I click on "Salva e Prosegui" and pass all the data to my ASP.MVC action in the controller.
I tried different ways but I'm not able to pass the images.
HTML:
<div class="fields-container">
<div class="row">
<div class="col-md-2">
<input type="text" name="nomecolore" placeholder="Nome Colore" class="form-control" />
</div>
<div class="col-md-1">
<input type="text" name="codicecolore" placeholder="Codice Colore" class="form-control" />
</div>
<div class="col-md-4">
<input type="file" name="filefronte" class="form-control filestyle" data-text="Foto Fronte" data-btnClass="btn-primary form-control" data-buttonBefore="true">
</div>
<div class="col-md-4">
<input type="file" name="fileretro" class="form-control filestyle" data-text="Foto Retro" data-btnClass="btn-primary form-control" data-buttonBefore="true">
</div>
<div class="col-md-1">
<button class="btn btn-success add-more form-control" type="button"><i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
JS:
$('#step-2-next').click(function () {
var ListaNomiColori = $(".fields-container :input[name=nomecolore]");
var ListaCodiciColori = $(".fields-container :input[name=codicecolore]");
var ListaImmaginiFronte = $(".fields-container :input[name=filefronte]");
var ListaImmaginiRetro = $(".fields-container :input[name=fileretro]");
var ID_Prodotto = "1";
for (i = 0; i < ListaNomiColori.length; i++) {
var formData = new FormData();
var nome = ListaNomiColori[i].value;
var codice = ListaCodiciColori[i].value;
var fronte = ListaImmaginiFronte[i].files[0];
var retro = ListaImmaginiRetro[i].files[0];
formData.append("NomeColore", nome);
formData.append("CodiceColore", codice);
formData.append("Foto", fronte);
formData.append("Foto", retro);
formData.append("ID_Prodotto", ID_Prodotto);
$.ajax({
url: _NuovoProdottoCaricaModelli,
data: formData,``
processData: false,
contentType: false,
success: function (res) {
alert('succes!!');
},
error: function (res) {
alert("errror");
}
})
}
});
Controller:
public JsonResult NuovoProdottoCaricaModelli(FormCollection form)
{
////code here
}
My logic is:
I get how many field sets I have and for each one I get the value and call the server for the upload. For each field set I have 2 text input, 2 file input. I also have to pass the ID to a third text field.
Thank you in advance.
Thanks to darloopkat. I found a way to do that.
Here below my edits:
js:
$('#step-2-next').click(function () {
var ListaNomiColori = $(".fields-container :input[name=nomecolore]");
var ListaCodiciColori = $(".fields-container :input[name=codicecolore]");
var ListaImmaginiFronte = $(".fields-container :input[name=filefronte]");
var ListaImmaginiRetro = $(".fields-container :input[name=fileretro]");
var ID_Prodotto = "1";
for (i = 0; i < ListaNomiColori.length; i++) {
var formData = new FormData();
var nome = ListaNomiColori[i].value;
var codice = ListaCodiciColori[i].value;
var fronte = ListaImmaginiFronte[i].files[0];
var retro = ListaImmaginiRetro[i].files[0];
formData.append("NomeColore", nome);
formData.append("CodiceColore", codice);
formData.append("Foto", fronte);
formData.append("Foto", retro);
formData.append("ID_Prodotto", ID_Prodotto);
$.ajax({
url: _NuovoProdottoCaricaModelli,
data: formData,
type: "POST",
processData: false,
contentType: false,
success: function (res) {
alert('succes!!');
},
error: function (res) {
alert("errror");
}
})
}
});
mvc action:
[HttpPost]
public ActionResult NuovoProdottoCaricaModelli()
{
string Nome = Request["NomeColore"];
string CodiceColore = Request["NomeColore"];
var Fronte = Request.Files[0];
var NomeFronte = Path.GetFileName(Fronte.FileName);
var Retro = Request.Files[1];
var NomeRetro = Path.GetFileName(Retro.FileName);
return Json("");
}

Could not Append to select tag by javascript and jquery

I am doing an mvc 5 project and I have cart view and I have 2 deopdownlist named country and state in it and when it is run the country model fill country dropdownlist and now I want to fill state dropdownlist onchange of country dropdownlist so I used code below to do this but it does not work successfully.i debug this code it works correctly the only problem is that this code can not append to state dropdownlist.I dont know what to do
#model IEnumerable<NewMVCWebApp.Models.Country>
<script>
function f11() {
var a = $("#se option:selected").text();
var b = $("#se option:selected").index();
$.ajax({
url: "/State/GetStates",
data: { a: a, b: b },
type:"post",
success: function (value) {
cities = JSON.parse(value);
$("#ss").html("");
$("#ss").append("<option>--- please select---</option>");
$.each(cities, function (idx, city) {
$("#ss").append("<option value='" + city.ID + "'>" + city.name + "</option>")
})
},
error: function () {
$("#lbl").html("Error in Ajax...!");
}
})
}
</script>
<div class="tabs-b">
<ul>
<li>estimate</li>
</ul>
<div>
<div>
<p>enter destination</p>
<p class="required">
<label for="sha">Country</label>
<select id="se" name="Country" onchange="f11()">
<option>--- please select ---</option>
#foreach (var item in Model)
{
<option value="#item.ID">#item.name</option>
}
</select>
</p>
<p class="required">
<label>region</label>
<select id="ss"></select>
</p>
<p>
<label for="shc">post code</label>
<input type="text" name="shc" id="shc" required="">
</p>
<p class="link-c">#*get*#</p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
</div>
</div>
the action in the controller
public string GetStates(string a,string b)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<state> states = _context.states.Where(x => x.IDK == Idk).ToList();
return js.Serialize(states.Select(x => new { ID = x.ID, name = x.name }));
}
In controller change method type to JsonResult
public JsonResult GetStates(int index)
{
JsonResult json = new JsonResult();
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
json.Data = _context.states.Where(x => x.IDK == index).ToList();
return json;
}
and in html file
function f11() {
var index = $("#se option:selected").val();
$.ajax({
url: "/State/GetStates",
data: { index: index },
type:"post",
success: function (value) {
var result = "";
$("#ss").append("<option>--- please select---</option>");
$.each(value, function (index, city) {
result += "<option value='" + city.ID + "'>" + city.name + "</option>";
});
$("#ss").append(result);
},
error: function () {
$("#lbl").html("Error in Ajax...!");
}
})
}

Categories