Laravel and Javascript - Deleting multiple rows from database - javascript

I am trying to delete several items from a database using checkboxes and javascript. The code I have already works and deletes the rows, however I am getting an error and that error actually prevents the page from refreshing and thus shwoing the updates results.
Here is what I have:
Route
Route::delete('/admin/videos/deleteselected', 'VideosController#deleteAllSelected')->name('videos.deleteAllSelected');
Controller
public function deleteAllSelected(Request $request)
{
$ids = $request->ids;
Video::where('id',explode(",",$ids))->delete();
//store status message
Session::flash('success_msg', 'Video(s) deleted successfully!');
return redirect()->route('videos.index');
}
View
<!-- videos list -->
#if(!empty($videos))
<div class="row text-center">
<div>
{{ $videos->links() }}
</div>
</div>
<div class="content table-responsive table-full-width">
<table class="table table-striped">
<button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="{{ route('videos.deleteAllSelected') }}">Delete All Selected</button>
<thead>
<th>ID</th>
<th><input type="checkbox" id="master"></th>
<th>Thumb</th>
<th>Duration</th>
<th>Manage</th>
</thead>
<!-- Table Body -->
<tbody>
#foreach($videos as $video)
<tr id="tr_{{$video->id}}">
<td>
<div>
{{$video->id}}
</div>
</td>
<td>
<div class="text-center">
<input type="checkbox" class="sub_chk" data-id="{{$video->id}}">
</div>
</td>
<td>
<div>
<img class="img-thumbnail" src="{{$video->imgurl}}" alt="video thumbnail">
</div>
</td>
<td>
<div>
{{$video->duration}}
</div>
</td>
<td>
<div><i class="fa fa-info"></i> Details</div>
<div><i class="fa fa-pencil"></i> Edit</div>
<div><i class="fa fa-trash"></i> Delete</div>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="row text-center">
{{ $videos->links() }}
</div>
#endif
Javascript Code
$(document).ready(function () {
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select videos.");
} else {
var check = confirm("Are you sure you want to delete this ?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".sub_chk:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
The error i get i cant actually copy it as it appears in a javascript alert. But please find attached an image of it:

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();
}

Delete data-id attribute value

I am new on javascript yet. I trying to delete value with data-id button, but data-id value is get always first value on my table. I click on the button with the data-id of "5" but as the id it is "1" (the topmost id) every time. Sorry my bad english.
My table codes:
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Category Name</th>
<th>Status</th>
<th>User</th>
<th>Management</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td><span class="label label-success">#item.ID</span></td>
<td>#item.CategoryName</td>
<td>#if (item.Status == true)
{
<b class="label label-success">Active</b>
}
else
{
<b class="label label-danger">Passive</b>
}
</td>
<td>#item.User.Name</td>
<td>
<button class="btn btn-default btn-sm">Edit</button>
<button class="btn btn-default btn-sm" id="btn-Delete" onclick="DeleteCategory()" data-id="#item.ID">Delete</button>
</td>
</tr>
}
</tbody>
</table>
My javascript codes:
function DeleteCategory() {
var caughtID= $("#btn-Delete").attr("data-id");
$.ajax({
url: "/Category/Delete/" + caughtID,
type: "POST",
dataType: "json",
success: function (response) {
if (response.Success) {
bootbox.alert(response.Message, function () {
location.reload();
});
}
else {
bootbox.alert(response.Message, function () {
//it's null yet
});
}
}
})
}
Id need to be unique, but in your case without id also it can be achievable, what you want to do.
Change:-
onclick="DeleteCategory()"
To:-
onclick="DeleteCategory(this)"
And then:-
function DeleteCategory(ele) {
var caughtID= $(ele).data("id");
.....rest code
DEMO EXAMPLE:-
function DeleteCategory(ele){
alert($(ele).data('id'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default btn-sm" id="btn-Delete" onclick="DeleteCategory(this)" data-id="1">Delete</button>
<button class="btn btn-default btn-sm" id="btn-Delete" onclick="DeleteCategory(this)" data-id="2">Delete</button>
<button class="btn btn-default btn-sm" id="btn-Delete" onclick="DeleteCategory(this)" data-id="3">Delete</button>
A pure jQuery solution is:-
change id="btn-Delete" to class ="btn-Delete" and remove onclick like below:-
<button class="btn btn-default btn-sm btn-Delete" data-id="#item.ID">Delete</button>
And then change only this line:-
var caughtID= $("#btn-Delete").attr("data-id");
To:-
var caughtID = $(this).data("id");
As Rory commented id attributes must be unique!. You should change the id of the button to class and make click on the static element. Because the button is dynamically created it may cause a problem that you are facing.
<button class="btn btn-default btn-sm btn-Delete" data-id="#item.ID">Delete</button>
$(document).ready(function() {
$('table').on('click', '.btn-Delete', function(event) {
event.preventDefault();
var caughtID = $(this).attr("data-id");
$.ajax({
url: "/Category/Delete/" + caughtID,
type: "POST",
dataType: "json",
success: function(response) {
if (response.Success) {
bootbox.alert(response.Message, function() {
location.reload();
});
} else {
bootbox.alert(response.Message, function() {
//it's null yet
});
}
}
})
});
});

Automatic scroll not working on click in angularJS

I have to scroll in a particular block(in may case table) when I will click on button.
vm.uploadOmrFile = function() {
vm.formSubmitted = true;
if (!vm.partners) {
return;
} else if (!vm.omrConfigurations) {
return;
} else if (!vm.schools) {
return;
} else if (!vm.classes) {
return;
}
formdata.append('classId', vm.configuration.classId);
// formdata.append('omrConfigId', vm.configuration.omrConfigId);
formdata.append('schoolId', vm.configuration.schoolId);
// formdata.append('tenantId', vm.configuration.tenantId);
var request = {
method: 'POST',
url: xxxxxx,
data: formdata,
transformRequest : angular.identity,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
vm.badrecords = 0;
vm.uploadresponse = d;
vm.records = d.studentAssessments;
vm.records.forEach(function(record){
if(record.output.type == 'invalid-csv') {
vm.badrecords += 1;
}
})
})
.error(function (error) {
toastr(error);
});
setTimeout(function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.path('/omr-upload');
$location.hash('message');
$anchorScroll();
}, 20000);
}
This is html file
<!doctype html>
<html>
<div class="modal-footer">
<button ng-click="vm.uploadOmrFile()" formnovalidate
class="btn btn-success" value="Upload"
dismiss="modal">Upload</button>
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
</div>
<tr>
<td class="nopadding noborder">
<table class="table">
<tr>
<td colspan="4">
<div class="alert alert-danger" id="message" ng-
if="vm.uploadresponse vm.uploadresponse.hasError"
role="alert">{{vm.uploadresponse.hasError}}
<strong>{{vm.uploadresponse.message}}</strong>
<br> Total Records Parsed:{{vm.records.length}}
<br>RecordsError: {{vm.badrecords}}
</div>
<div class="alert alert-success" id="message" ng-
if="vm.uploadresponse && !vm.uploadresponse.hasError">
<strong>{{vm.uploadresponse.message}}</strong>
<br> Total Records Parsed : {{vm.records.length}}
<br>Records with Error: 0
</div>
</td>
</tr>
<tr ng-if="vm.uploadresponse &&
vm.uploadresponse.hasError">
<th>Name</th>
<th>Sheet ID</th>
<th>Record Type</th>
<th>Messages</th>
</tr>
<tr ng-repeat="record in vm.records" ng-
if="vm.uploadresponse && vm.uploadresponse.hasError">
<td>{{record.name}}</td>
<td>{{record.omrsheet}}</td>
<td>{{record.output.type}}</td>
<td>
<div style="height:100px;overflow-y:scroll">
<div ng-repeat="msg in record.output.messages"
class="error">
<p>{{msg}}</p>
</div>
</div>
</td>
</tr>
<tr ng-if="vm.uploadresponse &&
!vm.uploadresponse.hasError">
<td>
<h2><i class="glyphicon glyphicon-thumbs-up" aria-
hidden="true"></i> All records fine!
<button class="btn btn-warning btn-lg" ng-
click="vm.saveOMR()">Click to Save OMR
data</button>
</h2>
</td>
</tr>
</table>
</td>
</tr>
</html>
My problem is when i Click to upload button It should go table section of html and upload button calling "uploadOmrFile()".
In my case scroll not going to table section.
I am using id as "message", which is uses location.hash.
setTimeout(function()
{
document.getElementById('message').scrollIntoView({block: 'start',
behavior: 'smooth'}); },1000);`
Paste This code After getting response

keep track of each $timeout when calling the same function multiple times

$scope.fetchStatus = function (job) {
$http
.get('http://gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
Here is my HTML code
<div ng-repeat="job in gtrLogs" class="each-log">
<div class="row job-id">
<div class="col-xs-2">
Job ID: {{job.jobId}}
</div>
<div class="col-xs-10">
End Point: {{job.changes.endpoint}}
</div>
</div>
<div class="each-job" ng-init="fetchStatus(job)">
<div class="job-header row">
<span class="col-xs-6">Job Status: <strong>{{job[job.jobId].status}}</strong>
<span class="glyphicon" ng-class="{'glyphicon-refresh spin' : job[job.jobId].status === 'InProgress', 'glyphicon-ok' : job[job.jobId].status === 'submitted', 'glyphicon-remove' : job[job.jobId].status === 'Aborted'}"></span>
</span>
<span class="col-xs-6">
<span class="glyphicon glyphicon-stop pull-right" ng-click="stopLogs()" tooltip="Stop Action"></span>
<span class="glyphicon glyphicon-repeat pull-right" ng-click="rollBack()" tooltip="Roll Back"></span>
</span>
</div>
<div class="logs-progress">
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th>
Message
</th>
<th>
Time
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in job[job.jobId].logs">
<td>{{row.msg}}</td>
<td>{{row.time | date:'yyyy/MM/dd HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I have to update the data every second and placed $timeout in the function. But because the function is being called multiple times from the HTML the calls are nested.
How Do I keep polling with respect to the same job.
Since you have a unique jobid, use can use that to maintain an array of key value pairs where your job id can correspond to a unique counter.
var counters = [];
$scope.fetchStatus = function (job) {
$http
.get('http://url:9090/gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
updateCounter(job.jobId);
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
function updateCounter(jobId) {
var exists = false,
jobId = parseInt(jobId);
for (var i in counters) {
if (counters[i].id === jobId) {
projects[i].counter++;
exists = true;
break;
}
}
if (!exists) {
counters.push({id: jobId, counter: 0});
}
}

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