Good day, i want to make when i select a value from any ddl , then a value next respective of each value input be displayed.image here. (https://i.stack.imgur.com/08DGz.png)
this is my html
<div class="row">
<div class="col-lg-6">
#Html.LabelFor(c => c.adaptadorJ)
#{ for (int i = 1; i <= 16; i++)
{
#Html.DropDownList("adaptadorJ" + i, itemAdaptadoresJs, "-J" + i + "-", new { #class = "form-control", #id = "J" + i, #onchange = "cambio(this)" })
}
}
</div>
<div class="col-lg-6">
#Html.LabelFor(c => c.asignaturaJ)
#{ for (int i = 1; i <= 16; i++)
{
#Html.TextBoxFor(c => c.asignaturaJ, new { #class = "form-control", #id = "asignaturaJInput" + i, autocomplete = "off", disabled = "disabled" })
}
}
</div>
</div>
this is my jquery ajax
function cambio(adaptador) {
var adaptadorID = adaptador.value;
$.ajax({
dataType: "json",
type: "POST",
url: '/Home/CambioAdaptador',
async: false,
data: {Adaptador: + adaptadorID },
success: function (result) {
$("#asignaturaJInput").val(result);
}
});
}
i used jquery, i just need to make that works.
Related
The below code generates 5 drop-down-lists.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } }) </td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty, "Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question", #style = "width:900px;" })</td>
</tr>
}
}
I am trying to populate the above 5 drop-down menu with a bunch of values I receive through my below ajax call
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
$("#Question").append('<option value="' + value.Question + '">' + value.Question + '</option>');
});
}
});
The above snippet only updates one of the drop-down list(the first drop-down menu) where it should be updating all five drop-down list.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } })</td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty,"Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question"+i, #style = "width:900px;" })</td>
</tr>
}
}
This will generate unique id as follows Question0, Question1, Question2, Question3, Question4
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
for(let j = 0; j < 5; j++){
$("#Question"+j).append('<option value="' + value.Question + '">' + value.Question + '</option>');
}
});
}
});
As I can see your loop is running through 5 iteration you can run it in the same way and append the data from ajax call. Or you can use starts with selector as follows
$('[id^=Question]').each(function(index,element){
$(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');
})
Hopefully this will solve your problem. Happy Coding!
This is my ViewComponet:
#model X.PagedList.PagedList<CbWebApp.DTOs.UsuarioDTO>
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Common
//.....more code
<div class="pagination-sm text-center">
Página #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de
#Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ListaUsuario", new { page = page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions { Display = PagedListDisplayMode.IfNeeded, MaximumPageNumbersToDisplay = 5 }, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "Get", UpdateTargetId = "usuariosPartial" }))
</div>
// more code....
My partialView that has the ViewComponent to be rendered and the DIV of reference:
<div id="usuariosPartial" class="col-xs-12 col-md-12">
#await Component.InvokeAsync("Usuario")
</div>
Maybe I can get the X.PagedList HTML id for JQuery for instance something like that:
// is this the correct id?
$("#pagesizelist").change(function (event) {
I tried that id but with no success. :(
Well, I found this solution but I am not sure if is the best approach:
JQuery - Give an ID to your table tr tag and reference it on the click event of an 'a' tag in jQuery as follows:
$('#replaceMyTr').on('click', 'a', function (e) {
e.preventDefault();
$("#icon").hide();
$("#progress").show();
$("#msg").hide();
$('input, button, a').disable(true);
var IdDoPerfilDoUsuario;
var este = $(this);
function getUrlVars() {
var vars = [], hash;
var hashes = este.attr("href").slice(este.attr("href").indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var page = getUrlVars()["page"];
if ($("select option:selected").first().val() === "--Todos--") {
IdDoPerfilDoUsuario = 0;
}
else {
IdDoPerfilDoUsuario = $("select option:selected").first().val();
}
$("#usuariosPartial").hide();
este.attr('disabled', 'disabled');
$.ajax({
url: "/Usuario/ListaUsuario",
type: 'GET',
cache: false,
data: { IdDoPerfilDoUsuario: IdDoPerfilDoUsuario, page: page },
success: function (result) {
$("#icon").show();
$("#progress").hide();
$("#msg").show();
$('input, button, a').disable(false);
$("#usuariosPartial").show();
$('#usuariosPartial').html(result);
}
});
return false;
});
View code:
// more code...
<tfoot>
<tr id="replaceMyTr">
#*<td colspan="7">*#
<td>
<div class="pagination-sm text-center">
#Html.PagedListPager((IPagedList)Model.Usuarios.ToEnumerable(), page => Url.Action("ListaUsuario", new { page = page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions { Display = PagedListDisplayMode.IfNeeded, MaximumPageNumbersToDisplay = 5 }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "teste" }))
</div>
</td>
</tr>
</tfoot>
//....more code
The issue I am facing is similar to this old post cascading dropdown for dynamically added row. I am using the "BeginCollectionItemCore" NuGet package to setup a set of partial views, so I have unique Id's for my controls. The problem is, I can only get the first Partial View to respond to the dropdownlist changes. The subsequent dropdownlists won't cascade. I have tried with the scripts in the partial and in the main view but both have the same end result, only the first partial will cascade. Here is my code...
Main View HTML:
#model IEnumerable<RCRTCWA.DATA.DAL.tbl_RCRTimeCards>
#{
ViewBag.Title = "Index";
}
<h2>Time Card</h2>
#using (Html.BeginForm())
{
<div id="TimeCardLines">
#foreach (var item in Model)
{
Html.RenderPartial("_TimeCardRow", item);
}
</div>
}
#Html.ActionLink("Add more time...", "_TimeCardRow", new { ViewContext.FormContext.FormId }, new { id = "addTime"})
Main View Script:
<script>
$(document).ready(function () {
debugger;
$("#addTime").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#TimeCardLines").append(html); }
});
return false;
});
//var index = "";
$(".timecardrow").focusin(function () {
var ti = $(this).find("[name='timecardrows.index']");
var index = ti.val();
$("#timecardrows_" + index + "__HRS_EndTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
$("#timecardrows_" + index + "__HRS_StartTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
//$("#.Line_TimeCard").ajaxSuccess(function () {
// $.getJSON("/TimeCard/AddTimeCardRow/", $("#.Success").html(data).show());
//});
$("#timecardrows_" + index + "__WOTicketNo").change(function () {
var tktid = $(this).val();
$("#timecardrows_" + index + "__WOTicketRepLineNo").empty();
$.ajax({
url: "/TimeCard/GetRepairLines/",
data: { ticket: tktid },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketRepLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("Error : " + response);
}
});
GetCarNumber(tktid);
});
$("#timecardrows_" + index + "__WOTicketRepLineNo").change(function () {
var line = $("#timecardrows_" + index + "__WOTicketRepLineNo").val();
$("#timecardrows_" + index + "__WOTicketLaborLineNo").empty();
$.ajax({
url: "/TimeCard/GetLineDetails/",
data: { lineid: line },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketLaborLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("error : " + response);
}
});
return false;
}).change();
function GetCarNumber(ticket) {
$.ajax({
url: "/TimeCard/GetCarNumber/",
data: { ticket: ticket },
cache: false,
type: "POST",
success: function (data) {
$("#timecardrows_" + index + "carNo").html(data).show();
},
error: function (response) {
alert("Error : " + response);
}
});
}
});
});
</script>
Partial View HTML:
#using HtmlHelpers.BeginCollectionItem
#model RCRTCWA.DATA.DAL.tbl_RCRTimeCards
<div class="timecardrow">
#using (Html.BeginCollectionItem("timecardrows"))
{
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table>
<tr>
<th class="col-sm-1">
Ticket Number
</th>
<th class="col-sm-1">
Car Number
</th>
<th class="col-sm-1">
Repair Line / Description
</th>
<th class="col-sm-1">
Labor Line / Description
</th>
<th class="col-sm-1">
Start Time
</th>
<th class="col-sm-1">
End Time
</th>
<th class="col-sm-1">
Line Complete?
</th>
</tr>
<tr>
<td class="form-group">
<div class="col-sm-1 tickets">
#Html.DropDownListFor(model => model.WOTicketNo, (SelectList)ViewData["TicketsList"], "Select one...", new { #class = "ticketddl" } )
#Html.ValidationMessageFor(model => model.WOTicketNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 cars">
<div id="carNo"></div>
#Html.HiddenFor(model => model.CarNo)
#Html.ValidationMessageFor(model => model.CarNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 replines">
#Html.DropDownListFor(model => model.WOTicketRepLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "repairddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 laborlines">
#Html.DropDownListFor(model => model.WOTicketLaborLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "lablineddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 starttime">
#Html.EditorFor(model => model.HRS_StartTime, new { #class = "start" })
#Html.ValidationMessageFor(model => model.HRS_StartTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 endtime">
#Html.EditorFor(model => model.HRS_EndTime, new { #class = "end" })
#Html.ValidationMessageFor(model => model.HRS_EndTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 completed">
#Html.EditorFor(model => model.Completed)
#Html.ValidationMessageFor(model => model.Completed, "", new { #class = "text-danger" })
</div>
</td>
#*<td class="form-group">
<div class="col-sm-1">
<input type="submit" value="Submit Line" class="btn btn-default" />
</div>
<div id="success" class="alert-danger">
</div>
</td>*#
</tr>
</table>
</div>
}
</div>
Currently I have the script in the Main View, and have attempted to get the index part of the partial view's controls when the user interacts with the partial view. I need a better way to handle this, and need to get the cascading dropdownlist's working properly.
I would prefer to have the script in the Main View (if possible) to keep things simpler.
You do not need to bind the change event handler on dropdown using concatenated id strings, which is prone to errors (typos etc) and not easily readable/maintainable. For your cascading dropdown scenario, all you care about is updating the second select element in the same row. jQuery has some handy methods like closest and find which will make our life easier.
For making it easier for future readers, I am going to assume that your first SELECT element is to render a list of countries and has a css class "countrySelect" and second one is for the states of selected country and has the css class "statesSelect" and both are in the same table row (<tr>).
When you bind the change event, make sure you use jQuery on to do so. This will enable the binding for current and future elements in the DOM .
$("#TimeCardLines").on("change","SELECT.countrySelect",function (e) {
var _this = $(this);
var v = _this.val();
// to do :Change below url variable value as needed for your code
var urlToGetSecondDropDownData = "/Home/GetStates?countryId"+v;
$.getJSON(urlToGetSecondDropDownData,
function (res) {
var items = "";
$.each(res,
function(index, item) {
items += "<option value='" + item.Value + "'>"
+ item.Text + "</option>";
});
_this.closest("tr") // Get the same table row
.find("SELECT.statesSelect") // Find the second dropdown
.html(items); // update the content of it
});
});
Assuming you have a GetStates action method which accepts a countryId param and return the corresponding states as a list of SelectListItem ( the data needed to build the second dropdown). Something like below,
public ActionResult GetStates(int countryId)
{
var states =db.States.Where(f => f.CountryId == countryId)
.Select(f => new SelectListItem() { Value = f.Id.ToString(),
Text = f.Name})
.ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
//first dropdowlist change event
$("#countryId").change(function () {
var id = this.value;
if (id == "") {
id = "0";
}
$.get('/Home/GetStates/' + id,
function (data) {
$('#stateId').find('option').remove()
$(data).each(
function (index, item) {
$('#stateId').append('<option value="' + item.Value + '">' + item.Text + '</option>')
});
}
);
});
public ActionResult GetStates(int id)
{
List<SelectListItem> StatesList= new List<SelectListItem>();
StatesList.Add(new SelectListItem { Text = "---Select State---", Value = "0" });
var getStateCollection= (from f in _ent.States
where f.CountryId == id && f.DeletedDate == null
select new { f.Id, f.Name}).ToList();
foreach (var item in getStateCollection)
{
StatesList.Add(new SelectListItem { Text = item.Name.ToString(), Value = item.Id.ToString() });
}
return Json(StatesList, JsonRequestBehavior.AllowGet);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a dropdownlist like this
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
it was like that because of this
<script type="text/javascript">
$(document).ready(function () {
$("#ddlGrade").change(function () {
var id = $(this).val();
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var select = $("#ddlSection");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Section"
}));
$.each(marksData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
and the JSON
public JsonResult PopulateDetails(string id)
{
List<Models.Section> a = new List<Models.Section>();
Models.ModelActions Ma = new ModelActions();
a = Ma.getSection(id);
var marksData = a.Select(c => new SelectListItem()
{
Text = c.sec_name,
Value = c.sec_id.ToString(),
});
return Json(marksData, JsonRequestBehavior.AllowGet);
}
now how can i add initial values to the dropdownlist in that format on postback? i need it for my search functionality. comments are much appreciated
EDITED:
VIEW:
<legend>CreateStudent</legend>
Full Name:
#Html.TextBox("searchTerm", null, new { id = "txtSearch" })
<input type="submit" value="search" name="submitbutton" />
<div class="editor-label">
#Html.LabelFor(model => model.si_id)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.si_id, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.si_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_fname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_fname)
#Html.ValidationMessageFor(model => model.si_fname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_mname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_mname)
#Html.ValidationMessageFor(model => model.si_mname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_lname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_lname)
#Html.ValidationMessageFor(model => model.si_lname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_gl_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_gl_id, new SelectList(Model.GradeLevel,"gl_id","gl_name"),"Select Grade Level", new { id = "ddlGrade" })
#Html.ValidationMessageFor(model => model.si_gl_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_sec_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
#Html.ValidationMessageFor(model => model.si_sec_id)
</div>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
</fieldset>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
Controller
[HttpPost]
public ActionResult RegisterStudent(CreateStudent Create, string submitbutton, string searchTerm)
{
acgs_qm.Models.ModelActions Ma = new acgs_qm.Models.ModelActions();
List<CreateStudent> stud = new List<CreateStudent>();
switch (submitbutton)
{
case "search":
ModelState.Clear();
var model = new CreateStudent
{
GradeLevel = Ma.getGrade(),
//Guardian = Ma.getGuardian(),
si_id = Ma.getStringval(searchTerm,"si_id","student_info_tb","si_fullname"),
si_fname = Ma.getStringval(searchTerm, "si_fname", "student_info_tb", "si_fullname"),
si_mname = Ma.getStringval(searchTerm, "si_mname", "student_info_tb", "si_fullname"),
si_lname = Ma.getStringval(searchTerm, "si_lname", "student_info_tb", "si_fullname"),
si_gender = Ma.getStringval(searchTerm, "si_gender", "student_info_tb", "si_fullname"),
};
return View("RegisterStudent",model);
case "Create":
if (ModelState.IsValid)
{
Ma.insertStudent(Create);
}
Create.GradeLevel = Ma.getGrade();
Create.si_id = Ma.getcode("student_info_tb", "si_id", "1");
return View(Create);
default:
return View(Create);
}
}
Change your implementation as follows :
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var $select = $("#ddlSection");
$select.empty();
$select.append('<option value=' + '0' + '>' + 'Select a Section' + '</option>');
$.each(marksData, function (index, itemData) {
$select.append('<option value=' + itemData.Value + '>' + itemData.Text + '</option>');
});
});
Try this
$("#ddlSection").change(function () {
var Id = this.value;
if (Id != 0) {
$.ajax({
type: "POST",
url: "/Employee/PopulateDetails",
data: JSON.stringify({ Id: Id }),
dataType: "text",
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
$("#ddlSection").empty();
$('#ddlSection').append("<option value='0'>Select Selection...</option>");
var yourArray = $.parseJSON(data);
if (yourArray != null) {
for (var i = 0; i < yourArray.length; i++) {
$('#ddlSection').append("<option value='" + yourArray[i].YourFiledName + "'>" + yourArray[i].YourFiledName + "</option>");
}
}
},
error: function (response) {
if (response != 1) {
alert("Error!!!!");
location.reload();
}
}
});
}
else {
alert("Please Select Any Value Name....");
}
});
I am passing model from view to controller. in my viewmodel List<TradeLaneDetailsDTO> is null always, and i am passing my data through ajax. what is the problem in my code.
please help me...
here is my viewmodel
public class SLAViewModel
{
public List<TradeLaneDetailsDTO> Items { get; set; }
}
here is my view
#using (Html.BeginForm("SaveSLA", "SLAMgmt", FormMethod.Post, htmlAttributes: new { #class = "form-horizontal", #role = "form", id = "frmEstDays" }))
{
for (int i = 0; i < Model.Items.Count; i++)
{
<div class="form-group">
#Html.LabelFor(model => model.Items.ElementAt(i).legname, Model.Items.ElementAt(i).legname, new { #class = "col-md-4" })
<div class="col-md-3">
#Html.TextBoxFor(model => model.Items.ElementAt(i).estddays, new { #class = "form-control", type = "text", MaxLength = "10" })
</div>
</div>
}
<div class="form-group">
<div class="offset-3 col-md-8">
<button id="btnSave" type="button" title="Save" class="btn btn-success" onclick="getPage1('#Url.Action("SaveSLA", "SLAMgmt")')">
<span class="glyphicon glyphicon-floppy-disk"></span>Save
</button>
</div>
</div>
}
and here is my ajax function
function getPage1(page)
{
alert("get page1");
$.ajax({
type: "POST",
url: page,
data: $("#frmEstDays").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
alert(html.responseText);
},
error: function (data) {
var error = "Error ";
}
});
}
here is my controller functions
public ActionResult SaveSLA(SLAViewModel slavModel)
{
string[] ErrorMessageArray = new string[4];
int errorIndex = 0;
return anything;
}
Simply use model=>model.Items[i].PROPERTYNAME as below
#Html.TextBoxFor(model => model.Items[i].estddays, new { #class = "form-control", type = "text", MaxLength = "10" })
hope this will help
Please remove type = "text" from TextBoxFor html helper.
#Html.TextBoxFor(model => model.Items.ElementAt(i).estddays, new { #class = "form-control", MaxLength = "10" })
The HtmlTextboxFor always creates a textbox <input type="text" />. So you don't have to specify explicitly.