Table TH not displaying correctly after onchange evernt fires - javascript

So I'm trying to hide the Company Name <th> column when the employee drop down is selected.
I have this jQuery function that I've been trying to figure out for sometime now and cant seem to get it working. I've tried to walk though script with FF debugger but nothing happens, with no errors. Im kind of lost on where to take it from here.
DropDown
#using (Html.BeginForm())
{
#Html.DropDownList("SearchStatus", new SelectList(ViewBag.SearchStatusList, "Value", "Text", ViewBag.SelectedItem), new { #class = "form-control", #onchange = "form.submit();" })
}
jQuery
<script type="text/javascript">
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus option:selected").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});
VIEW
#model PagedList.IPagedList<Login.Models.EditProfile>
#using PagedList.Mvc;
#{
ViewBag.Title = "Pending Accounts";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<style>
... deleted CSS that was here
</style>
<h2>Pending Accounts</h2>
#using (Html.BeginForm())
{
#Html.DropDownList("SearchStatus", new SelectList(ViewBag.SearchStatusList, "Value", "Text", ViewBag.SelectedItem), new { #class = "form-control", #onchange = "form.submit();" })
}
<br />
<table class="table grid">
<tr>
<th>
<b>Options</b>
</th>
<th>
First Name:
</th>
<th>
Last Name:
</th>
<th>
Email:
</th>
<th>
Phone Number:
</th>
<th id="hidden_div" style="display: none;">
Company Name:
</th>
<th></th>
</tr>
#foreach (var item in Model.ToList())
{
<tr>
<td>
<div class="btn-group">
<button type="button" id="bootstrap-ok" class="btn btn-default btn-sm icon-success">
<span class="glyphicon glyphicon-ok "></span>
</button>
<button type="button" id="bootstrap-danger" class="btn btn-default btn-sm icon-danger">
<span class="glyphicon glyphicon-remove "></span>
</button>
</div>
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
#if (item.CompanyName != null)
{
<td>
#Html.DisplayFor(ModelItem => item.CompanyName)
</td>
}
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("PendingAccounts", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
#if (Request.IsAuthenticated)
{
using (Html.BeginForm("Logout", "User", FormMethod.Post, new { id = "logoutForm" }))
{
Logout
}
}
<script type="text/javascript">
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus option:selected").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});

you can get the value of the dropdown by using $(yourDropdown).val() and not selecting the options. So try this:
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});

Related

How to Call Partial View with Asp.Net Mvc

I need to search on the database, and load only the View, and not refresh the entire page. A function in Js calls my method on the controller, when clicking on search, and the controller returns the View.
function Pesquisa()
{
let campo = document.getElementsByName("campo");
let pesquisa = document.getElementsByName("EdtPesquisa");
let condicao = document.getElementsByName("pesquisa");
let scampo = Array();
let spesquisa = Array();
let scondicao = Array();
let sNomeGrid = ($(this).find("a").text());
for (var indice = 0; indice < pesquisa.length; indice++)
{
string = pesquisa[indice].value;
if (string.trim() != "")
{
scampo[indice] = campo[indice].id;
scondicao[indice] = condicao[indice].value;
spesquisa[indice] = pesquisa[indice].value;
}
}
window.location.href = "/MenuPrincipal/RetornarView?sNomeGrid=" + "Unidade" + "&listacampo=" + scampo + "&listacondicao=" + scondicao + "&listapesquisa=" + spesquisa;
Controller
public IActionResult RetornarView(string sNomeGrid, List<string> listacampo, List<string> listacondicao, List<string> listapesquisa)
{
var sWhere = "";
if (listacampo.Count > 0)
{
Pesquisa _Pesquisa = new Pesquisa();
sWhere = _Pesquisa.Pesquisar(listacampo, listacondicao, listapesquisa);
}
if (sNomeGrid == "Unidade")
{
var listaunidade = _UnidadeRepositorio.ListarMenu(sWhere);
return View("Unidade", listaunidade);
}
return View("MenuPrincipal");
}
View
#model IEnumerable<ApesWeb.Models.Classes.Unidade>
<div class="tabela-responsive">
<table id="tabela" class="tabela tabela-hover"
data-toggle="table">
<thead>
<tr>
<th id="idunidade" name="campo">#Html.DisplayNameFor(model => model.idunidade)</th>
<th id="sdescricao" name="campo">#Html.DisplayNameFor(model => model.sdescricao)</th>
<th id="sunidade" name="campo">#Html.DisplayNameFor(model => model.sunidade)</th>
<th id="sdigitavolume" name="campo">#Html.DisplayNameFor(model => model.sdigitavolume)</th>
<th id="spadraosistema" name="campo">#Html.DisplayNameFor(model => model.spadraosistema)</th>
</tr>
<tr>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa"/>
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
</tr>
</thead>
<tbody>
#foreach (var Unidade in Model)
{
<tr>
<td>
#Html.DisplayFor(modelitem => Unidade.idunidade)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sdescricao)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sunidade)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sdigitavolume)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.spadraosistema)
</td>
</tr>
}
</tbody>
</table>
Returns the View with the list to fill the Table, but in this process the entire page is refreshed.
You can use one of the following methods according to your needs:
Method I: If you want to use ViewData, try this:
#Html.Partial("~/PathToYourView.cshtml", null,
new ViewDataDictionary { { "VariableName", "some value" } })
And to retrieve the passed in values:
#{
string valuePassedIn = this.ViewData.ContainsKey("VariableName") ?
this.ViewData["VariableName"].ToString() : string.Empty;
}
Method II: If you just render a partial with just the partial name:
#Html.Partial("_SomePartial", Model)
Method II: Render PartialView using jQuery Ajax call:
Firstly wrap your body content in a div and assign any id to it in _Layout page:
<div id="div-page-content" class="page-content">
#RenderBody()
</div>
Here is the menu item used for rendering PartialView in _Layout page:
<ul class="sub-menu">
<li class="nav-item ">
<a href="#" onclick="renderPartial(event, 'Account', '_Register')" class="nav-link">
<span class="title">Create New User</span>
</a>
</li>
</ul>
Define the javascript function for click event in _Layout page:
function renderPartial(e, controller, action) {
e.preventDefault();
e.stopPropagation();
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
////Open url in new tab with ctrl key press
//if (e.ctrlKey) {
// window.open(url, '_blank');
// e.stopPropagation();
// return false;
//}
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#div-page-content").html(data);
},
error: function (data) { onError(data); }
});
};
Define your PartialView as shown below:
<div>
... partial view content goes here >
</div>
Add the Action metdod to the Controller as shown below:
[HttpPost]
[AllowAnonymous]
public PartialViewResult _Register(/* additional parameters */)
{
return PartialView();
}

How to add or remove records from table on click add button, and send all table rows to controller on submit?

I'm sharing image of my task:
I have issue that, when I clicked on Add Button all fields data will display in table below, and I want to add multiple products to this table, also if user wants to remove any product from table then clicked on remove button.
After add products when user clicked on submit then all record send to controller method.
I'm sharing some code which I'm trying to do.
View Code
<div class="row">
<div class="col-md-12">
<div class="tile">
<div>
<h1><i class="fa fa-th-list"></i> Inventory</h1>
<p>Issu Products to Unit</p>
</div>
#Html.Partial("~/Views/Shared/_ErrorMsgPartial.cshtml")
<div class="tile-body">
<span style="color:red; font-weight:bold;">Note: Dont Enter Quantity Morethan Availabale Quantity</span>
#using (Html.BeginForm("IssueProduct", "Inventory", FormMethod.Post, new { #id = "formPost" }))
{
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Available Qty</th>
<th>Issue Qunatity</th>
<th>Unit</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
#Html.DropDownList("productId", null, "Select One", htmlAttributes: new { #class = "form-control", id = "demoSelect" })
#Html.ValidationMessageFor(model => model.productId, "", new { #class = "text-danger" })
</td>
<td id="GetAvlbQty" style="font-weight: bold;color: red;text-align: center;">
#{Html.RenderPartial("GetAvlbQty", Model);}
</td>
<td>
#Html.EditorFor(model => model.invQty, new { htmlAttributes = new { #class = "form-control", id = "invcQty", #PlaceHolder = "Enter Quantity To Issue" } })
#Html.ValidationMessageFor(model => model.productId, "", new { #class = "text-danger" })
</td>
<td>
#Html.DropDownListFor(model => model.invUnit, new List<SelectListItem>
{
new SelectListItem{Text="Unit A",Value="Unit A"},
new SelectListItem{Text="Unit B",Value="Unit B"},
}, "Select Unit", htmlAttributes: new { #class = "form-control", id = "unit" })
#Html.ValidationMessageFor(model => model.invUnit, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.invDescription, new { htmlAttributes = new { #class = "form-control", id = "descrip", #PlaceHolder = "Enter Description" } })
#Html.ValidationMessageFor(model => model.invDescription, "", new { #class = "text-danger" })
</td>
<td>
<button type="button" id="btnAdd" class="btn btn-outline-success btn-s classAdd">Add</button>
</td>
</tr>
</tbody>
</table>
<table id="tablePost" class="table table-hover table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Available Qty</th>
<th>Issue Qunatity</th>
<th>Unit</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="submit" class="btn btn-outline-success btn-sm" value="Save" />
}
</div>
</div>
</div>
</div>
Here is some jQuery code but it just add product to row. Not remove and also not send into controller. I don't need to send data through HIDDEN FIELDS.
$(document).ready(function () {
$("#btnAdd").on("click", function () {
var demoSelect = $("#demoSelect :selected").text();
var invcAvlbQty = $("#availableQty").val();
var invcQty = $("#invcQty").val();
var unit = $("#unit :selected").val();
var descrip = $("#descrip").val();
$("#tablePost > tbody").append("<tr><td>" +
demoSelect + "</td><td>" + invcAvlbQty + "</td><td>" + invcQty + "</td><td>" + unit + "</td><td>" + descrip + "</td></tr>");
});
});
How can I resolve this?
Create table from you want to add the record in list-
<div>
<table>
<tr>
<td><input type="text" id="txt1"/></td>
<td><input type="submit" id="btnAdd" value="Add"/></td>
</tr>
</table>
</div>
<div>
<table id="tbldata"> </table>
</div>
<div>
<input type="submit" id="btnsubmit" value="Save"/>
</div>
this function is used for add record in list on button add click
$('#btnAdd').click(function(){
if (!localStorage.count) {
localStorage.count = 0;
}
localStorage.count++;
var num = localStorage.count;
var TextVal=$('#txt1').val();
$('#tbldata').append('<tr id=' + num + '><td>'+TextVal+'</td>
<td><a
href="javascript:void(0)"
onclick="Removerow(' + num + ')" >Remove</a></td></tr>')
})
this function is used for remove the row from table in list
function Removerow(id)
{
$("#"+id+"").remove();
}
this function is used for get al the record from list added in table
$('#btnsubmit').click(function(){
GetRecord();
})
function GetRecord()
{
var table = $("#tbldata");
//find all table tr value usnig each loop
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
ItemName = $tds.eq(0).val();
SaveRecord(ItemName);
}
this function is used for save record in db
function SaveRecord(ItemName) {
$.ajax({
type: 'GET',
dataType: 'json',
url: "Controllername/actionname",
data: { _ItemName : ItemName },
success: function (Data) {
localStorage.clear();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
}
Hope it will help you.

Passing Data in wizard form without post back in MVC

Sorry for any mistake. I am new to MVC. I want to pass data from one wizard form to other in single view. Below is my controller side code which return list to view. In view there is wizard form where i make update some field in list and on next button i want to pass all changed data to next wizard form in table.
public ActionResult PlaceOrder()
{
OrderDetail ObjOrderDetails = new OrderDetail();
try
{
DataSet ds = new DataSet();
ds = GeneralHelper.GetUserDocumentDetail(1);
List<OrderModel> objOrder = ds.Tables[0].ToList<OrderModel>();
ObjOrderDetails.OrderDetails = objOrder;
}
catch (Exception ex)
{
throw ex;
}
return View(ObjOrderDetails);
}
Below is my view side Code
<div class="tab-content">
<div class="tab-pane" id="details">
<div class="row">
<div class="col-sm-12">
<h4 class="info-text">
Let's start with the basic details.</h4>
</div>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<div class="persons">
<table class="table table-condensed table-hover" id="tblPurchaseOrders">
<tr>
<th>
Product Code
</th>
<th>
SKU
</th>
<th>
Product Name
</th>
<th>
Quantity
</th>
</tr>
#{
//To make unique Id int i = 0;
foreach (var item in Model.OrderDetails.ToList())
{
<tr>
<td>
#Html.EditorFor(o => o.OrderDetails[i].ProductCode, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
</td>
<td>
#Html.EditorFor(o => o.OrderDetails[i].SKU, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
</td>
<td>
#Html.EditorFor(o => o.OrderDetails[i].Name, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
</td>
<td>
#Html.EditorFor(o => o.OrderDetails[i].Quantity, new { #id = "Quantity_" + i })
</td>
</tr>
i++; } }
</table>
</div>
</div>
</div>
<hr />
</div>
</div>
</div>
<div class="tab-pane" id="captain">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<table class="table table-condensed table-hover" id="tbOrderDetail">
<tr>
<th>
Product Code
</th>
<th>
SKU
</th>
<th>
Product Name
</th>
<th>
Quantity
</th>
</tr>
</table>
</div>
</div>
</div>
</div>
Below is my jquery code.
$('#rootwizard').bootstrapWizard({
onTabShow: function(tab, navigation, index) {
if (index == 1) {
$(".persons > table").each(function() {
var fields = $(this).find(":text");
alert(fields)
var name = fields.eq(-1).val();
var age = fields.eq(1).val();
alert(name);
});
}
}
});
I want to loop all rows of #tblPurchaseOrders and want to append all the rows to #tbOrderDetail where quantity is greater than 0.
You can do it like below:
$('#rootwizard').bootstrapWizard({
onTabShow: function(tab, navigation, index) {
if (index == 1) {
$('#tblPurchaseOrders').find('tr:has(td)').each(function() {
if (parseInt(($(this).find('#Quantity')).val()) > 0)
$(this).appendTo('#tbOrderDetail');
});
}
}
});
Online Demo (jsFiddle)

Jquery disable to affect all items in model if textbox empty

So my code is below. I need to disable the IsShortlisted editor for if both or one of the DateManagerNotified and DateManagerReplied fields are blank. This currently works but it only affects the first iteration in the model list.
#model IEnumerable<Recruitment.Model.VacancyApplicant>
#{
ViewBag.Title = "Shortlistings";
}
<h2>Unprocessed Applicants for #Html.ActionLink(#Model.First().Vacancy.JobRef, "Details", "Vacancy", new { id = Model.First().VacancyId }, null)</h2>
#using (Html.BeginForm("Shortlist", "VacancyApplicant", FormMethod.Post))
{
#Html.AntiForgeryToken()
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>
#Html.ActionLink("First Name", "Shortlist", new { sort = ViewBag.FirstNameSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Last Name", "Shortlist", new { sort = ViewBag.LastNameSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Date Received", "Shortlist", new { sort = ViewBag.DateReceivedSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Date Manager Notified", "Shortlist", new { sort = ViewBag.DateManagerNotifiedSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Date Manager Replied", "Shortlist", new { sort = ViewBag.DateManagerRepliedSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Shortlisted?", "Shortlist", new { sort = ViewBag.IsShortlistedSort, vacancyId = Model.First().VacancyId })
</th>
<th>
#Html.ActionLink("Email?", "Shortlist", new { sort = ViewBag.EmailSort, vacancyId = Model.First().VacancyId })
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.TextBoxFor(modelItem => item.Applicant.FirstName, new { #class = "form-control", disabled = "disabled" })
</td>
<td>
#Html.TextBoxFor(modelItem => item.Applicant.LastName, new { #class = "form-control", disabled = "disabled" })
</td>
<td>
#Html.TextBoxFor(modelItem => item.DateReceived, "{0:dd/MM/yyyy}", new { #class = "form-control", disabled = "disabled" })
</td>
<td>
<span id="datenotified">
<div class="input-group">
#Html.EditorFor(modelItem => item.DateManagerNotified, new { htmlAttributes = new { #class = "form-control date-picker", placeholder = "Datepicker..." }, })
<label class="input-group-addon btn">
<span class="fa fa-calendar"></span>
</label>
</div>
</span>
</td>
<td>
<span id="datereplied">
<div class="input-group">
#Html.EditorFor(modelItem => item.DateManagerReplied, new { htmlAttributes = new { #class = "form-control date-picker", placeholder = "Datepicker..." }, })
<label class="input-group-addon btn">
<span class="fa fa-calendar"></span>
</label>
</div>
</span>
</td>
<td>
<span id="shortlisted">
#Html.EditorFor(modelItem => item.IsShortlisted, "NullBool")
</span>
</td>
<td>
#if (string.IsNullOrEmpty(item.Applicant.EmailAddress))
{
#Html.CheckBox("EmailAddress", false, new { #class = "form-control", #disabled = "disabled" });
}
else
{
#Html.CheckBox("EmailAddress", true, new { #class = "form-control", #disabled = "disabled" });
}
</td>
</tr>
}
</tbody>
</table>
<div class="center-block form-group">
<div class="text-center">
<div class="button-container">
<input type="submit" name="PrintRegret" value="Print Regret" class="btn btn-danger" />
<input type="submit" name="Save" value="Save" class="btn btn-primary" />
<input type="submit" name="EmailRegret" value="Email Regret" class="btn btn-danger" />
</div>
<br />
#Html.ActionLink("Print Applicants for Shortlisting", "PrintApplicantsForShortlisting", "VacancyApplicant", new { VacancyId = Model.First().Vacancy.VacancyId }, new { #class = "btn btn-success" })
#Html.ActionLink("Email Applicants for Shortlisting", "EmailApplicantsForShortlisting", "VacancyApplicant", new { VacancyId = Model.First().Vacancy.VacancyId }, new { #class = "btn btn-success" })
<br /><br />
#Html.ActionLink("Shortlist By File", "AutoShortlist", "Interview", new { vacancyId = Model.First().Vacancy.VacancyId }, null)<br />
#Html.ActionLink("Interviews", "InterviewsByVacancy", "Interview", new { VacancyId = Model.First().Vacancy.VacancyId }, null)
</div>
</div>
}
My Jquery is
$("#datereplied :input").on("change", function() {
if ($(this).val() != "") {
console.log("replied not disabled");
$("#shortlisted :input").prop("disabled", false);
} else {
console.log("replied disabled");
$("#shortlisted :input").prop("disabled", "disabled");
}
})
$("#datenotified :input").on("change", function () {
if ($(this).val() != "") {
console.log("notified not disabled");
$("#shortlisted :input").prop("disabled", false);
} else {
console.log("notified disabled");
$("#shortlisted :input").prop("disabled", "disabled");
}
})
As you can see I'm using span to disable the isshortlisted option list. This only ever affects the first one on the page.
cheers for any help
an id must be unique.
Change all the id's in the foreach to classes, then use:-
$(this).closest('tr').find(".shortlisted :input").prop("disabled", false);

Execute Script on Partial View

I have the following script in my Main View which works great to create cascading dropdownlists. However, I cannot get it to execute on the partial view after it is loaded. From what I have read online, it seems that I need some sort of Ajax call in the partial view (which I am completely clueless on how to write). Any Assistance would be greatly appreciated.
<script type="text/javascript">
$(function () {
$("#SelectedCollateralClass").change(function () {
var selectedItem = $(this).val();
var ddlTypes = $("#SelectedCollateralType");
var typesProgress = $("#types-loading-progress");
typesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetCollateralTypesByClass"))",
data: { "CollateralClassId": selectedItem },
success: function (data) {
ddlTypes.html('');
$.each(data, function (id, option) {
ddlTypes.append($('<option></option>').val(option.id).html(option.name));
});
typesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve types.');
typesProgress.hide();
}
});
});
});
</script>
My Main View is:
#model CollateralRowViewModel
<div class="APPLICATION">
#*#Html.Partial("_SideBarView.cshtml");
#Html.Partial("_CommentsView.cshtml");*#
<!-- Content ======================================================================================-->
<div class="container row">
#using (#Html.BeginForm())
{
<div class="col-xs-16">
<div class="hr">
<h3 class="inline-block"> Collateral</h3>
<a class="icon-add"></a>
</div>
<table class="dataentry">
<thead>
<tr>
<th>#Html.LabelFor(model => model.CollateralClass)</th>
<th>#Html.LabelFor(model => model.CollateralType)</th>
<th>#Html.LabelFor(model => model.Description)</th>
<th>#Html.LabelFor(model => model.MarketValue)</th>
<th>#Html.LabelFor(model => model.PriorLiens)</th>
<th>#Html.LabelFor(model => model.AdvanceRate)</th>
<th>#Html.Label("Grantor (if not Borrower)")</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="inputROW">
#Html.DropDownListFor(model => model.SelectedCollateralClass, Model.CollateralClass)
</span>
</td>
<td>
<span class="inputROW">
#Html.DropDownListFor(model=>model.SelectedCollateralType, Model.CollateralType)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model => model.Description)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model => model.MarketValue)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model => model.PriorLiens)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model => model.AdvanceRate)
</span>
</td>
<td>
<span class="inputROW Smargin_bottom">
#Html.TextBoxFor(model => model.GrantorFirstName)
</span>
<span class="inputROW">
#Html.TextBoxFor(model => model.GrantorMiddleName)
</span>
<span class="inputROW">
#Html.TextBoxFor(model => model.GrantorLastName)
</span>
</td>
<td class="minusRow">
<a class="btn btn-danger icon-subtract sm btn-xs" data-nodrag ng-click="remove(this)"></a>
</td>
</tr>
</tbody>
</table>
<div>
<input id="addBtn" type="button" value="Add New Collateral" />
</div>
</div>
}
</div> <!-- end container -->
<footer id="APPfooter">
<div class="pagination centerF">
<ul>
<li class="previous"></li>
<li class="next"></li>
</ul>
</div>
</footer>
</div><!-- end page content container-->
<script type="text/javascript" charset="utf-8">
$(function () {
$('.default').dropkick();
$( "#datepicker" ).datepicker();
});
</script>
<script>
$("#addBtn").on("click", function () {
$.get('#Url.Action("AddNewRow")', function (data) {
$("table").append(data);
});
});
</script>
<script type="text/javascript">
$(document).ready(
$(function () {
$("#SelectedCollateralClass").change(function () {
var selectedItem = $(this).val();
var ddlTypes = $("#SelectedCollateralType");
var typesProgress = $("#types-loading-progress");
typesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetCollateralTypesByClass"))",
data: { "CollateralClassId": selectedItem },
success: function (data) {
ddlTypes.html('');
$.each(data, function (id, option) {
ddlTypes.append($('<option></option>').val(option.id).html(option.name));
});
typesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve types.');
typesProgress.hide();
}
});
});
}));
</script>
My partial looks like:
#model CollateralRowViewModel
<tr>
<td>
<span class="inputROW">
#Html.DropDownListFor(model=>model.SelectedCollateralClass, Model.CollateralClass)
</span>
</td>
<td>
<span class="inputROW">
#Html.DropDownListFor(model=>model.SelectedCollateralType, Model.CollateralType)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model=>model.Description)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model=>model.MarketValue)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model=>model.PriorLiens)
</span>
</td>
<td>
<span class="inputROW">
#Html.TextBoxFor(model=>model.AdvanceRate)
</span>
</td>
<td>
<span class="inputROW Smargin_bottom">
#Html.TextBoxFor(model=>model.GrantorFirstName)
</span>
<span class="inputROW">
#Html.TextBoxFor(model=>model.GrantorMiddleName)
</span>
<span class="inputROW">
#Html.TextBoxFor(model=>model.GrantorLastName)
</span>
</td>
<td class="minusRow">
<a class="btn btn-danger icon-subtract sm btn-xs" data-nodrag ng-click="remove(this)"></a>
</td>
</tr>
The Controller Action is:
[AcceptVerbs(HttpVerbs.Get)]
public async Task<ActionResult> GetCollateralTypesByClass(Guid collateralClassId)
{
var collateralServiceProxy = base.ServiceProvider.CollateralServiceProxy;
var collateralTypes = await collateralServiceProxy.GetCollateralTypesByCollateralClassIdAsync(collateralClassId);
var selectCollateraltypes = (from t in collateralTypes
select new
{
id = t.Id.ToString(),
name = t.Name
}).ToList();
return Json(selectCollateraltypes, JsonRequestBehavior.AllowGet);
}
The Partial is being called by a button "Add New" as follows:
<script>
$("#addBtn").on("click", function () {
$.get('#Url.Action("AddNewRow")', function (data) {
$("table").append(data);
});
});
</script>
The Controller for the button is :
[HttpGet]
[Route("CreateRow")]
public async Task<ActionResult> AddNewRow()
{
var collateralClasses = await GetCollateralClasses();
var collateralTypes = await GetCollateralTypes();
var model = new CollateralRowViewModel();
model.CollateralClass.Add(new SelectListItem { Text = "-Please Select-", Value = "-1" });
foreach (var _class in collateralClasses)
{
model.CollateralClass.Add(new SelectListItem()
{
Value = _class.Value.ToString(),
Text = _class.Text.ToString()
});
}
model.CollateralType.Add(new SelectListItem { Text = "-Please Select-", Value = "-1" });
foreach (var type in collateralTypes)
{
model.CollateralType.Add(new SelectListItem()
{
Value = type.Value.ToString(),
Text = type.Text.ToString()
});
}
return PartialView("_newCollateralRow", model);
}
I got the answer. All I needed to do was to add new{#class = "ddlClass'} and new {#class = "ddlType"} to the Partial. Then I just copied the script to the Partial and changed the references from referencing the Id to referencing the new classes as below:
<script type="text/javascript">
$(function () {
$(".ddlClass").change(function () {
var selectedItem = $(this).val();
var ddlTypes = $(".ddlType");
var typesProgress = $("#types-loading-progress");
typesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetCollateralTypesByClass"))",
data: { "CollateralClassId": selectedItem },
success: function (data) {
ddlTypes.html('');
$.each(data, function (id, option) {
ddlTypes.append($('<option></option>').val(option.id).html(option.name));
});
typesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve types.');
typesProgress.hide();
}
});
});
});
</script>
I hope this helps someone else!

Categories