Execute Script on Partial View - javascript

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!

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

Laravel and Javascript - Deleting multiple rows from database

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:

Table TH not displaying correctly after onchange evernt fires

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

Value of other column in the row in dynamic row is not changing

I have a dynamic row here and I have created a drop down of product and I want that price is changed automatically when the drop down is selected.
<div>
#using (Html.BeginForm("SaveProduct", "Master", FormMethod.Post, new { #id = "frmProductDetail", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// #Html.Hidden("ProductOrderId", Model.ProductOrderId)
// #Html.Hidden("ProductId", Model.ProductId)
<div class="row-fluid border-light-color">
<div class="padding-5">
<div class="span12">
<div class="clear"></div>
<div class="Col1">
<span>#Html.LabelFor("Customer Name"):</span>
</div>
<div class="Col2">
#Html.TextAreaFor(m => m.CustomerName, new { #name = "CustomerName", #id = "CustomerName", #class = "txtCustDetails" })
</div>
<div class="Col3">
<span>#Html.LabelFor("Contact Number"):</span>
</div>
<div class="Col4">
#Html.TextAreaFor(m => m.CustomerNumber, new { #name = "CustomerName", #id = "CustomerName", #class = "txtCustDetails" })
</div>
<div class="clear"></div>
<div class="Col1">
<span>#Html.LabelFor("FirstName"):</span>
</div>
<div class="row-fluid">
Add
</div>
<div class="row-fluid">
<table class="table table-bordered table-hover gridtable" id="tblProduct" showsequence="true">
<thead>
<tr>
<th style="width:20%">SR No.</th>
<th style="width:20%">Product Name</th>
<th style="width:20%">Rate</th>
<th style="width:20%">Quantity</th>
<th style="width:20%">Grand Total</th>
<th style="width:20%">Delete</th>
</tr>
</thead>
<tbody>
<tr id="0" style="display:none">
<td class="text-center"></td>
<td>
#Html.DropDownList("ProductId", Model.ProductName.ToSelectList(Model.ProductNameId.ToString(), "Name","Value"))
</td>
<td>
#Html.TextBoxFor(m=>m.priceDetail, new { #name = "ProductPrice1", #id = "ProductPrice1", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.OrderQuantity, new { #name = "OrderQuantity", #id = "OrderQuantity", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.GrandTotal, new { #name = "GrandTotal", #id = "GrandTotal", #class = "txtCustDetails"})
</td>
<td class="text-center vertical-middle">
<i class="icon-trash" ></i>
</td>
</tr>
<tr id="1">
<td class="text-center">1</td>
<td>
#Html.DropDownList("ProductId", Model.ProductName.ToSelectList(Model.ProductNameId.ToString(), "Name", "Value"))
</td>
<td>
#Html.TextBoxFor(m=>m.priceDetail, new { #name = "ProductPrice2", #id = "ProductPrice2", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.OrderQuantity, new { #name = "OrderQuantity", #id = "OrderQuantity", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.GrandTotal, new { #name = "GrandTotal", #id = "GrandTotal", #class = "txtCustDetails"})
</td>
<td class="text-center vertical-middle">
<i class="icon-trash" ></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
}
</div>
I am trying to do it through Jquery but I am having problem that the price changes automatically only in the first row and not in the other rows. Please help me so that it changes in every row individually.
var GetPriceUrl = BASEPATHURL + "/Master/GetPriceDetail";
jQuery(document).ready(function () {
jQuery('#btnAdd').on('click', function () { AddRow('#tblProduct') });
//jQuery('#btnSave').on('click', function () { SaveEmployees() });
jQuery('#tblProduct').on('click', "a[name='RemoveRow']", function () { RemoveRow(this) });
jQuery("#tblProduct tbody").sortable({
//handle: '.glyphicon-move',
update: function () {
Reorder('#tblProduct');
}
});
jQuery("select[name]*=ProductId").change(function () {
GetPriceByProductId(jQuery(this).val());
jQuery(this).css('border-color', '');
});
});
function AddRow(tableId) {
var row = jQuery(tableId + ' > tbody > tr:first').clone(true);
var index = parseInt(jQuery(tableId + ' > tbody > tr:visible').length);
jQuery("input, textarea, select", row).each(function () {
jQuery(this).attr("id", jQuery(this).attr("id") + "_" + (index + 1));
jQuery(this).val('');
});
jQuery(tableId).append(row);
jQuery(row).show().attr("id", index);
Reorder(tableId);
}
function RemoveRow(control) {
var tableId = "#" + jQuery(control).closest("table").attr("id");
jQuery(control).closest("tr").remove();
jQuery(tableId + ' > tbody > tr:visible').each(function (i, e) { jQuery(e).attr("id", i + 1) });
Reorder(tableId);
}
function Reorder(tableId) {
jQuery(tableId + '[showSequence = "true"] > tbody > tr:visible').each(function (i, e) {
jQuery(this).find("td:first").text(i + 1);
});
}
function GetPriceByProductId(ProductId) {
if (jQuery.trim(ProductId) != ""){
var postData = { ProductId: ProductId };
AjaxCall({
url: GetPriceUrl,
postData: postData,
httpmethod: 'POST',
calldatatype: 'JSON',
sucesscallbackfunction: 'OnSucessGetProductById'
});
}
}
function OnSucessGetProductById(response) {
jQuery("#ProductPrice2").val('');
jQuery("#ProductPrice2").val(response.priceDetail[0].ProductPrice);
}
Well I found the solution to this. Posting so that it may help others (sick of no response :( ). I saw that my AddRow function was incrementing the ProductId by 1. so firstly I took the Id of it and acquired its substring, then I concatenated it with the pricedetail so that it changes with every row. i have provided the function below.
jQuery("select[name]*=ProductId").change(function () {
var xyz = jQuery(this).attr("id");
Pro_Id = xyz.substring(xyz.lastIndexOf('_'));
GetPriceByProductId(jQuery(this).val());
jQuery(this).css('border-color', '');
jQuery('#btnSave').on('click', function () { InsertProductDetail(); });
jQuery('#btnUpdate').on('click', function () { InsertProductDetail(); });
});
function OnSucessGetProductById(response) {
//Jquery("input[name^='PriceDetail']").split('_').val("");
if (Pro_Id == "ProductId") {
jQuery("#ProductPrice").val('');
jQuery("#ProductPrice").val(response.priceDetail[0].ProductPrice);
}
else {
jQuery("#ProductPrice" + Pro_Id).val('');
jQuery("#ProductPrice" + Pro_Id).val(response.priceDetail[0].ProductPrice);
}
Pro_Id = "";
}
I hope this helps anyone in future. Thanks.

MVC 4 Changing a field based on DropDownListFor selection

I have a form that has a dropdownlist that is made up of different course names and a textbox that will contain the number of the next course section based on the dropdown selection and its highest existing section number in the database. After a selection is made the javascript will get called, then call my controller method to figure out which section number it should be, and then fill the textbox.
My dropdownlist: Controller
ViewBag.CourseList = new SelectList(db.CourseLists, "CourseTitle", "CourseTitle");
My dropdownlist: View
#Html.DropDownListFor(model => model.CourseTitle,
new SelectList(#ViewBag.CourseList, "Value", "Text"), " -- Select Course -- ", new { #id = "CourseTitle", onchange = "CourseChange()" })
#Html.ValidationMessageFor(model => model.CourseTitle)
Textbox:
#Html.EditorFor(model => model.ClassNumber, new { #id = "ClassNumber" })
#Html.ValidationMessageFor(model => model.ClassNumber)
Javascript functions:
<script type="text/javascript">
function CourseChange() {
var courseTitle = $('#CourseTitle').val(); //Is always null
$.getJSON("NextClassNumber", courseTitle, updateClassNumber);
};
updateClassNumber = function (data) {
$('#ClassNumber').val(data);
};
</script>
When I make a change my method in my controller is called and passes back a value and sets my textbox, but the value for the selected item is coming through as null. Any ideas as to why?
::::EDIT::::
#model QIEducationWebApp.Models.Course
#{
ViewBag.Title = "Add New Course";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
$(function () {
$('#CourseTitle').on('change', function () {
var courseTitle = $(this).val();
$.ajax({
url: '#Url.RouteUrl(new{ action="NextClassNumber", controller="Course"})',
data: { courseTitle: courseTitle },
type: 'get'
}).done(function (data) {
$('#ClassNumber').val(data);
});
});
});
</script>
<h1 class="page-header">#ViewBag.Title</h1>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<table class="table">
<tr>
<th class="table-row">
Course Title:
</th>
<td class="table-row">
#Html.DropDownListFor(model => model.CourseTitle1,
#ViewBag.CourseList as SelectList, " -- Select Course -- ", new { #class="form-control", #id="CourseTitle" })
#Html.ValidationMessageFor(model => model.CourseTitle)
</td>
</tr>
<tr>
<th class="table-row">
Class Number:
</th>
<td class="table-row">
#Html.EditorFor(model => model.ClassNumber, new { #id = "ClassNumber" })
#Html.ValidationMessageFor(model => model.ClassNumber)
</td>
</tr>
<tr>
<th class="table-row">
Course Type:
</th>
<td class="table-row">
#Html.DropDownList("CourseType", " -- Select Type -- ")
#Html.ValidationMessageFor(model => model.CourseType)
</td>
</tr>
<tr>
<th class="table-row">
Start & End Date:
</th>
<td class="table-row">
#Html.EditorFor(model => model.CourseStartDate)
#Html.ValidationMessageFor(model => model.CourseStartDate)
</td>
<td class="table-row">
#Html.EditorFor(model => model.CourseEndDate)
#Html.ValidationMessageFor(model => model.CourseEndDate)
</td>
</tr>
<tr><td class="table-row-blank"></td></tr>
<tr>
<td class="table-row-button">
<input class="button" type="submit" value="Create" />
<input type="button" class="button" value="Cancel"
onclick="location.href='#Url.Action("Index")'" />
</td>
</tr>
</table>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
your code should work fine if the select list is being generated correctly.
I would use part of the suggestion above and use
#Html.DropDownListFor(model => model.CourseTitle,
(SelectList)ViewBag.CourseList,
" -- Select Course -- ",
new { onchange = "CourseChange()" })
using another good suggestion already mentioned you can change your script to use on instead
<script type="text/javascript">
$(function () {
$('#CourseTitle').on('change', function () {
var courseTitle = $(this).val();
$.getJSON("NextClassNumber", courseTitle, function (data) {
$('#ClassNumber').val(data);
});
});
});
</script>
here is a dotnetfiddle example. DotNetFiddle
You can pass reference of dropdownlist from the onchange event :
onchange = "CourseChange"
and in js function:
function CourseChange(element) {
var selected = element.Value;
// or
var selected = $(element).val();
and a side note you don't need to construct SelectList again on View just cast it from ViewBag:
#Html.DropDownListFor(model => model.CourseTitle,
#ViewBag.CourseList as SelectList,
"-- Select Course --",
new { onchange = "CourseChange" })

Categories