I have a model and a View with a select and a few text boxes. I am trying to bind the textbox values to the selected list item the following way:
Model:
public class Items
{
public string ID { get; set; }
public string Name { get; set; }
public SelectList ItemList { get; set; }
public List<SelectListData> MiscList { get; set; }
}
public class SelectListData{
public string ID { get; set; }
public string Name { get; set; }
public string Address{get; set;}
public string City{get; set;}
public string State{get; set;}
}
Controller:
Controller:
public async public async Task<IActionResult> Index()
{
Items viewModel = new Items();
List<SelectListData> tempLIst = new List<SelectListData>();
tempLIst.Add(new SelectListData() { ID = "1", Name = "ID-1", Address="123 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "2", Name = "ID-2", Address="234 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "3", Name = "ID-3", Address="345 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "4", Name = "ID-4", Address="456 AVE", City = "New City", State = "CA"});
viewModel.ItemList = new SelectList(tempLIst, "ID", "Name", 2);
viewModel.SelectListData = tempLIst;
return View(viewModel);
}
View:
#Model Items
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control" onchange="OnSelectedIndexChanged_01(this)"></select>
</div>
#{
if(Model.ID != null) {
var selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ID).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" /> =====? how do I set the value to selectedAddress here?
</div>
</div>
</div>
<script>
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList()); ===? this is being assigned correctly
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out
//myArray = jsdata;
console.log("[" + selectedID + "] [" + jsdata + "] [" + myArray + "]"); ===> this line is printing [[object, object], [object, object], [object, object]]
//console.log("[" + selectedID + "] [" + jsdata + "]");
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].ID == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].Address.toString();
break;
}
}
}
</script>
I am trying to bind the selectedValue of the dropdown to a selected Address. Any help is appreciated.
Edit:
As ScareCrow indicated, I am able to bind the initial values.
ANother question: my javascript doesn't seem to populate the address text based on the OnChange event of the dropdownlist. I am not sure if I am passing the model's arraylist properly. Any pointers is helpful.
Thanks
NH
Please try the following code Snippet in view: made changes in your code
#model Items;
#{var selectedAddress=string.Empty;}
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control"></select>
</div>
#{
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" />
</div>
</div>
</div>
I believe the selected items you set in
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
rather than Model.ID in your code.
Dropdown change event can be achieved by the following Javascript code snippet:
$(document).ready(function () {
$('#ID').change(function () {
var selectedValue = $(this).val();
var misclist = #Json.Serialize(#Model.MiscList.ToList());
for(i=0;i<misclist.length;i++){
if(misclist[i].id == selectedValue) {
$('#selAddress').val(misclist[i].address);
break;
}
}
});
});
There were 2 issues with my question. #ScareCrow provided a solution to my first issue and helped me in figuring out the solution to my second issue. Here's an updated javascript function(with the key values being lower-case):
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList());
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out; jsdata is already a javascript object
myArray = jsdata;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].id == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].address.toString();
break;
}
}
}
Related
I am just starting to work with asp.net mvc and I am trying to understand the logic between views and controllers.
I have the table with the data that I am getting from the db shown on my page and I am also have the dropdown on my page. I would like to update my table according to the value selected from the dropdown (for example if user selects T3) the data for T3 shows in the table.
I can't quite understand how I can pass the value selected from the dropdown and how to the controller and how to update my sql query with this new value. Is it suppose to be in the same index method or it should be the different one. I would appreciate any help and ideas. Thank you in advance.
Here is my model:
public class TestModel
{
public int id { get; set; }
public string name { get; set; }
public string serial{ get; set; }
public string pr { get; set; }
}
Here is my Controller: First sql string I am using to get data for the dropdown and the second one to get data for the table itself.
public class TestController : Controller
{
public List<TestModel> Test = new List<TestModel>();
public List<TableModel> Table = new List<TableModel>();
public IActionResult Index()
{
try
{
String connectionString = "bbbb";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String sql2 = "SELECT * FROM db WHERE detail = 1";
using (SqlCommand command = new SqlCommand(sql2, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
TestModel test= new TestModel();
test.id = Convert.ToInt32("" + reader[0]);
test.name = "" + reader[1];
test.serial = "" + reader[3];
test.pr = "" + reader[4];
Test.Add(test);
}
}
}
String sql = "SELECT * FROM bb1";
using (SqlCommand command1 = new SqlCommand(sql, connection)) {
using(SqlDataReader reader1 = command1.ExecuteReader())
{
while (reader1.Read())
{
TableModel tablemod = new TableModel();
tablemod.id = Convert.ToInt32("" + reader1[0]);
tablemod.tr = "" + reader1[2];
tablemod.pr = "" + reader1[4];
tablemod.req = "" + reader1[5];
tablemod.test = "" + reader1[6];
tablemod.method = "" + reader1[7];
tablemod.sport = "" + reader1[8];
tablemod.timer = "" + reader1[9];
tablemod.ra = "" + reader1[10];
tablemod.calib = "" + reader1[12];
Table.Add(tablemod);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("exception:" + ex.ToString());
}
ViewData["dropdown"] = TestCell;
ViewData["table"] = Table;
return View();
}
}
And here is the view:
<!doctype html>
<html lang="eng">
<head>
some styles go there
</head>
<body>
<div class="table">
<div>
<select asp-for="#Model.id" asp-items="(#ViewData["dropdown"] as IEnumerable<SelectListItem>)" id="UserId" class="form-control " >
<span asp-validation-for="#Model.id"></span>
#foreach (var item in #ViewData["dropdown"] as IEnumerable<TestModel>)
{
<option class="others" value="#item.id&&#item.serial&&#item.pr">#item.fname</option>
}
</select>
</div>
<div><input id="serial" type="text"/></div>
<div><input id="pr" type="text"/></div>
</div>
</div>
<table class="table ">
<thead>
<th data-field="tr" data-sortable="true">TR</th>
<th data-field="pr" data-sortable="true">Priority</th>
<th data-field="req" data-sortable="true">Requestor</th>
<th data-field="test" data-sortable="true">Test Name</th>
<th data-field="method" data-sortable="true">Description</th>
<th data-field="sport" data-sortable="true">Failed Part</th>
<th data-field="timer" data-sortable="true">Emission</th>
<th data-field="ra" data-sortable="true">Rating</th>
<th data-field="calib" data-sortable="true">Calibration</th>
</thead>
<tbody>
#foreach (var item in #ViewData["table"] as IEnumerable<TableModel>)
{
<tr>
<td>#item.trnum</td>
<td>#item.priority</td>
<td>#item.requestor</td>
<td>#item.testname</td>
<td>#item.description</td>
<td>#item.failed</td>
<td>#item.emission</td>
<td>#item.rating</td>
<td>#item.calibration</td>
<td>#item.eas</td>
<td>#item.recorder</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
var $table = $('#fresh-table')
var $alertBtn = $('#alertBtn')
$(function () {
$table.bootstrapTable({
classes: 'table table-hover table-striped',
toolbar: '.toolbar',
search: true,
showRefresh: true,
showToggle: true,
showColumns: true,
pagination: true,
height: $(window).height(),
striped: true,
sortable: true,
pageSize: 10,
pageList: [8, 10, 25, 50, 100],
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return ''
},
formatRecordsPerPage: function (pageNumber) {
return pageNumber + ' rows visible'
}
})
$(window).resize(function () {
$table.bootstrapTable('resetView', {
height: $(window).height(),
})
})
})
$(function () {
$('#fresh-table').bootstrapTable()
})
$("#UserId").change(function () {
var selectedid = $("#UserId option:selected").val().split("&&");
var serialNumber = selectedid[1];
var projectNumber = selectedid[2];
$('#serialNumber').val(serialNumber);
$('#projectNumber').val(projectNumber);
});
</script>
I have 2 properties created, one with a masked value and the other with a raw value for my web page. Currently when I submit the form I have the masked value to display with the eyeball slash. When I click on the eyeball I want the raw value to be displayed and masked again when clicked. None of the research online explains this, they only focus on passwords which I do not need.
index.cshtml.cs
// Properties
public ResidencyCheckResult CheckResult { get; set; }
public string OutputSSN { get => CheckResult.SSNumber; set => CheckResult.SSNumber = value; }
public string OutputSSNMasked { get; set; }
// Constructors(Parameters)
public IndexModel(Assess50Context context)
{
_context = context;
CheckResult = new ResidencyCheckResult();
}
// Methods(Parameters)
public async Task<IActionResult> OnPostSubmit()
{
using HttpClient client = new HttpClient();
ResidencyCheckClient checkClient = new ResidencyCheckClient();
await checkClient.OpenAsync();
ResidencyCheckCriteria checkCriteria = new ResidencyCheckCriteria()
{
};
ResidencyCheckResult checkResult = await checkClient.ValidateFloridaResidencyAsync(checkCriteria);
OutputSSN = checkResult.SSNumber;
OutputSSNMasked = OutputSSN;
OutputSSN = $"{SubstringCheck(OutputSSN, 3)}-{SubstringCheck(OutputSSN, 3, 2)}-{SubstringCheck(OutputSSN, 5, 4)}";
OutputSSNMasked = $"{SubstringCheck(OutputSSNMasked, 3)}-{SubstringCheck(OutputSSNMasked, 3, 2)}-{SubstringCheck(OutputSSNMasked.Replace(OutputSSNMasked, "XXXX"), 5, 4)}";
await checkClient.CloseAsync();
return Page();
}
// methods to prevent causing argument out of range exceptions on substring calls
public string SubstringCheck(string s, int length)
{
int len = s.Length;
if (len > length)
{
len = length;
}
return s.Substring(0, len);
}
public string SubstringCheck(string s, int b, int length)
{
int len = s.Length;
if (len <= b)
{
return s;
}
len -= b; // b < len
if (len > length)
{
len = length;
}
return s.Substring(b, len);
}
index.cshtml
<form class="mt-0" method="post">
<button class="btn btn-outline-dark col-1 offset-5" type="submit" id="SubmitBtn" name="SubmitBtn" value="Submit" disabled asp-page-handler="Submit">Submit</button>
<input class="form-control" title="Social security number" readonly asp-for="OutputSSNMasked">
<i class="fa fa-eye-slash" id="ToggleOutputSSN" style="cursor: pointer;"></i>
</form>
#section Scripts {
<script>
const toggleOutputSSN = document.querySelector('#ToggleOutputSSN');
const outputSSNMasked = document.querySelector('#OutputSSN');
toggleOutputSSN.addEventListener('click', function (e) {
const type = outputSSNMasked.getAttribute('type') === 'text' ? 'password' : 'text';
outputSSNMasked.setAttribute('type', type);
this.classList.toggle('fa-eye');
});
});
</script>
Try something like this.
const toggleOutputSSN = document.querySelector('#ToggleOutputSSN');
const outputSSNMasked = document.querySelector('#OutputSSNMasked');
toggleOutputSSN.addEventListener('click', function(e) {
const parts = outputSSNMasked.dataset.ssn.split('-');
if(!outputSSNMasked.value.endsWith('XXXX')) {
parts[2] = 'XXXX';
}
outputSSNMasked.value = parts.join('-');
const iTag = this.querySelector('i');
iTag.classList.toggle('fa-eye');
});
.masked-input {
margin: 20px;
width: 200px !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group masked-input">
<input type="text"
id="OutputSSNMasked"
class="form-control"
title="Social security number"
aria-label="Social security number"
data-ssn="115-67-0707"
value="115-67-0707">
<span id="ToggleOutputSSN" class="input-group-text" style="cursor: pointer;">
<i class="far fa-eye-slash"></i>
</span>
</div>
I have three dropdownlists that I fill with the contents of viewbag variables. I want the content of the second variable to be filtered when I select a value of the first using JQuery or javascript. The same with the third dropdownlist, which is filtered by what is selected in the second.
<script type="text/javascript">
function SelectedIndexChanged(accion, idnum) {
var nuevaSelProyecto = "";
var proyecto = "";
var nombre = "";
switch (idnum) {
case "ddlSelContrato": {
//var getValue = document.getElementById('ddlSelContrato').selectedOptions[0].value;
var e = document.getElementById("ddlSelContrato");
var getValue = e.options[e.selectedIndex].value;
nombre = "Contrato, indice seleccionado: " + getValue;
};
break;
case "ddlSelProyecto":
nombre = "Proyecto";
break;
case "ddlPtoStudio":
nombre = "Punto Estudio";
default:
nombre = "Defecto";
break;
}
alert("Alerta, indice: " + accion + " - " + nombre);
}
</script>
<div>
<text style="margin-left: 8px;">
  Contrato  
</text>
#*--------------------Listado desplegable de Contrato--------------------------*#
#Html.DropDownList("ddlSelContrato", new SelectList(ViewBag.SelContrato, "Id", "Nombre"), new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)" })
</div>
<div>
<text style="margin-left: 8px;">
  Proyecto  
</text>
#*--------------------Listado desplegable de Proyecto--------------------------*#
#Html.DropDownList("ddlSelProyecto", new SelectList(ViewBag.SelProyecto, "Id", "Nombre"), new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)"})
</div>
<div>
<text style="margin-left: 8px;">
  Punto de Medicion  
</text>
#*--------------------Listado desplegable de Puntos de estudio--------------------------*#
#Html.DropDownList("ddlPtoStudio", new SelectList(ViewBag.PtoStudio, "Id", "Nombre"), new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)" })
</div>
Controller:
// GET: PuntoEstudios
public IActionResult Index()
{
ViewBag.SelContrato = _context.Contratos.OrderByDescending(x=>x.Nombre).ToList(); //Variable MVC donde paso a la vista el List de los Contratos
ViewBag.SelProyecto = _context.Proyectos.ToList(); //Variable MVC donde paso a la vista el List de los Proyectos
ViewBag.PtoStudio = _context.PuntoEstudios.ToList(); //Variable MVC donde paso a la vista el List de los pto de estudio
return View();
}
How can I do it without calling the server
I assume that the relationships between your three models like : Contrato-Proyecto(one-to-many),Proyecto-PtoStudio(one-to-many) . If you want to change the filter the value of dropdownlist without calling the server, you could refer to the below working demo:
Models
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<StudyPoint> StudyPoints { get; set; }
[ForeignKey("Contact")]
public int ContactId { get; set; }
public Contact Contact { get; set; }
}
public class StudyPoint
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Product")]
public int ProductId { get; set; }
public Product Product { get; set; }
}
Controller , use Include() to load the related data
public IActionResult CascadeDropdownlist()
{
ViewBag.SelContrato = _context.Contact.OrderByDescending(x => x.Name).ToList();
ViewBag.SelProyecto = _context.Product.Include(p=>p.Contact).ToList();
ViewBag.PtoStudio = _context.StudyPoint.Include(s=>s.Product).ToList();
return View();
}
View and the javascript , refer to https://sung.codes/blog/2018/02/24/approximate-equivalent-linq-methods-javascript/ to use linq in javascript
#{
ViewData["Title"] = "CascadeDropdownlist";
}
<h1>CascadeDropdownlist</h1>
<div>
<text style="margin-left: 8px;">
  Contact  
</text>
#*--------------------Listado desplegable de Contrato--------------------------*#
#Html.DropDownList("ddlSelContrato", new SelectList(ViewBag.SelContrato, "Id", "Name"),"Select value" ,new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)" })
</div>
<div id="">
<text style="margin-left: 8px;">
  Product  
</text>
#*--------------------Listado desplegable de Proyecto--------------------------*#
#Html.DropDownList("ddlSelProyecto", new SelectList(ViewBag.SelProyecto, "Id", "Name"),"Select value" , new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)" })
</div>
<div>
<text style="margin-left: 8px;">
  Study point  
</text>
#*--------------------Listado desplegable de Puntos de estudio--------------------------*#
#Html.DropDownList("ddlPtoStudio", new SelectList(ViewBag.PtoStudio, "Id", "Name"),"Select value" , new { Class = "ddlStyle", onchange = "SelectedIndexChanged(this.value ,id)" })
</div>
#section Scripts
{
<script type="text/javascript">
function SelectedIndexChanged(action, idnum) {
var nuevaSelProyecto = "";
var proyecto = "";
var name = "";
switch (idnum) {
case "ddlSelContrato": {
//var getValue = document.getElementById('ddlSelContrato').selectedOptions[0].value;
var e = document.getElementById("ddlSelContrato");
var array = #Html.Raw(Json.Serialize(ViewBag.SelProyecto));
var getValue = e.options[e.selectedIndex].value;
var projectdata = array.filter(a => a.contactId == getValue);
$("#ddlSelProyecto").empty();
$('#ddlSelProyecto').append($("<option value=0>Select value</option>"));
projectdata.forEach(function (e) {
$('#ddlSelProyecto').append($("<option></option>").attr("value",e.id).text(e.name));
});
};
break;
case "ddlSelProyecto":
{
//var getValue = document.getElementById('ddlSelContrato').selectedOptions[0].value;
var e = document.getElementById("ddlSelProyecto");
var array = #Html.Raw(Json.Serialize(ViewBag.PtoStudio));
var getValue = e.options[e.selectedIndex].value;
var projectdata = array.filter(a => a.productId == getValue);
$("#ddlPtoStudio").empty();
$('#ddlPtoStudio').append($("<option value=0>Select value</option>"));
projectdata.forEach(function (e) {
$('#ddlPtoStudio').append($("<option></option>").attr("value",e.id).text(e.name));
});
};
break;
case "ddlPtoStudio":
name = "Punto Estudio";
default:
name = "Defecto";
break;
}
}
</script>
}
Result
I code to generate captcha at page load. Here is the code.
protected void Page_Load(object sender, EventArgs e)
{
Bitmap objBMP = new System.Drawing.Bitmap(60, 20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Green);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
Font objFont = new Font("Arial", 10, FontStyle.Italic);
string randomStr = "";
int[] myIntArray = new int[5];
int x;
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9));
randomStr += (myIntArray[x].ToString());
}
Session.Add("randomStr", randomStr);
objGraphics.RotateTransform(-7F);
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
Response.ContentType = "image/Gif";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
Now I want to validate between inputed value and generated captcha. Just like as
if (Page.IsValid && (txtInput.Text.ToString() == Session["randomStr"].ToString()))
Here I have saved query.of user using four text boxes.
public static string SaveEnquiry(string name, string email, string contact, string comments, string Company, string items, string ip,string captcha)
{
string StrReturn = "";
try
{
UserContactUs objUserContactUs = new UserContactUs();
string userCmt = "User Comment:" + comments; ;
int result = objUserContactUs.insertContactUs(name, contact, email, userCmt, GetUser_IP());
if (result > 0)
{
string mesageRec = name + " has enquired for " + ". Contact : " + contact + ", Email: " + email+ ". His Cmt: " + comments ;
//SendSMSToAdmin(mesageRec);
//SendSMSToUser(contact.TrimStart('0'));
StrReturn = "1#Thanks, for your interest.We will get back to you soon";
}
else
{
StrReturn = "0#Your enquiry is not saved. Please try Again!";
}
}
catch (Exception ex)
{
StrReturn = "0#" + ex.Message;
}
return StrReturn;
}
Now I want is if both the fields(i.e captcha image and inputtext box) are not equal then refresh the captcha image by showing a message invalid captcha.
Here is my contact form.
<div class="col-sm-2">
<img height="50" id="EnquiryCaptcha" alt="" style="border:inset;" src="InsertEnquiry.aspx" width="130">
</div>
<div class="col-sm-15">
<input type="text" name="txtInput" id="txtInput" placeholder="Captcha*" style="margin-top:auto; border:groove;">
</div>
<!--end-->
<button class="border-button " data-animation="fadeInUp" data-animation-delay="1000" type="button" id="btnsubmit" onclick="InsertEnquiry('contactForm')" name="submit">Send Message</button>
The label that is beings created holds a guid that I need later. I need to grab that information after the list of labels are created. Here's my code:
<button onclick="getAllListings()">Get All Listings Information</button>
<br />
<div id="divDataInsert" name="divDataInsert">
#foreach (MVCTest1.Models.Listing foundListings in Model._listings)
{
string pk_listing_id = "listingsid_" + foundListings.PK_Listings_ID;
string addressPK = "address_" + foundListings.PK_Listings_ID;
string address = foundListings.Address.ToString();
string cityPK = "city_" + foundListings.PK_Listings_ID;
string city = foundListings.City.ToString();
string statePK = "state_" + foundListings.PK_Listings_ID;
string state = foundListings.State.ToString();
string zipcodePK = "zipcode_" + foundListings.PK_Listings_ID;
string zipcode = foundListings.ZipCode.ToString();
string fullAddress = address + ", " + city + " " + state;
if (foundListings.PK_Listings_ID != null)
{
<input type="text" id="lblListing_#pk_listing_id" value="#pk_listing_id" />
}
}
</div>
function getAllListings(){
//var listingArray = [document.getElementById("lblListing_")];
for (var i = 0; i < [document.getElementById("lblListing_")].length; i++) {
var listingString = document.getElementById("lblListing_").value;
var guid = listingString.split("_");
alert(guid[1]);
i++;
}
}
My code behind
public ActionResult Index()
{
string sql = "SELECT TOP 10 [PK_Listings_ID], [Address], [City], [State], [ZipCode] FROM dbo.Listings";
ListingCollection ListOfListings = new ListingCollection();
ListOfListings._listings = new List<Listing>();
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MVCInsertData"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sql;
using(SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
Listing listing = new Listing();
listing.PK_Listings_ID = Convert.ToInt32(reader["PK_Listings_ID"]);
listing.Address = reader["Address"].ToString();
listing.City = reader["City"].ToString();
listing.State = reader["State"].ToString();
listing.ZipCode = reader["ZipCode"].ToString();
ListOfListings._listings.Add(listing);
}
}
}
}
conn.Close();
}
return View(ListOfListings);
}
one of the answers involved adding a JS array in the code behind. How do you do that?
*****Update*****
I have changed my input to this:
<input type="text" class="lblListing_" value="#pk_listing_id" />
And I have adjusted my JS to this:
function getAllListings(){
var listingsArray = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listingsArray.length; i++) {
var listingString = listingsArray.value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Keep in mind, my JS is NOT inside a document.ready(). Should it be?
One way would be to have your code behind emit a JavaScript array of all labels. A different--and this is the approach I would take--would be to use a class name as a "tag". Emit:
<input type="text" class="lblListing_" ...>
Then in your fixed (not dynamic) JavaScript, you can do:
function getAllListings(){
var listings = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listings.length; i++) {
var listingString = listings[i].value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Update for the follow-on question:
The JavaScript can be placed anywhere but will not run on load. When and how to run the function depends on what you need it to do. (I assume the alert is just to test the logic.)
You can easily achieve that with jQuery
$('someSelector').each(function() {
// do something
});
$("input[id^='lblListing_']").each(function() {
console.log($(this).val().split("_")[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="lblListing_g-u-i-d-1" value="value1_g-u-i-d-1" />
<input type="text" id="lblListing_g-u-i-d-2" value="value2_g-u-i-d-2" />