Passing selected dropdown string value from table in view to controller - javascript

I'm working on ASP.NET Core web application where I have a table in my view that displays all requests. each record with drop-down populated with all analysts successfully from my database, So the manager can assign the analyst from drop-down then approve the request.
My questions:
Can I implement this using form for each record instead using JavaScript, I mean using only asp tags?
If that should done using JavaScript, Here is my attempt to implement this.
The following code is working only if the Analyst id is integer, but in my case the analyst id is string, so whenever I try to execute this, I got either "null" or "Zero" for the analyst id in the controller. Here is my ViewModel
public class RequestViewModel
{
public IEnumerable<Request> Requests { get; set; }
public IEnumerable<ApplicationUser> AnalystList { get; set; }
public Institution Institution { get; set; }
public string selectedAnalyst { get; set; }
}
Here is my controller
public async Task<IActionResult> ApproveRequest(int id, int Analystid)
{
Request Req = await _db.Request
.Include(c => c.Institution)
.FirstOrDefaultAsync(c => c.Id == id);
if (Req.Type == SD.TypeRegister)
{
Req.Institution.Status = SD.StatusApproved;
Req.Institution.ApprovalDate = DateTime.Now;
Req.Institution.Seats = Req.Seats; // new
Req.Institution.AnalystId = Analystid.ToString(); //Here I want to get the id as string
}
else if (Req.Type == SD.TypeSeat)
{
Req.Institution.Seats += Req.Seats;
}
else if (Req.Type == SD.TypeSubscription)
{
Req.Institution.Seats = Req.Seats;
Req.Institution.Status = SD.StatusApproved;
Req.Institution.ApprovalDate = DateTime.Now;
}
Req.isDone = true;
await _db.SaveChangesAsync();
return await CreateApproval(id, SD.StatusApproved);
}
Here is my View
#model TestApplication.Models.ViewModels.RequestViewModel
#using TestApplication.Extensions
#{
ViewData["Title"] = "Index";
}
<div class="tab-pane fade show active" id="Register" role="tabpanel" aria-labelledby="Register-tab">
Registration Requests
<div>
#if (Model.Requests.Count() > 0)
{
<table class="table table-striped">
<tr class="table-secondary">
<th>
Institution Name
</th>
<th>
Date
</th>
<th>
Actual seat
</th>
<th>
Seats
</th>
<th>
New Seat
</th>
<th>
Choose Analyst
</th>
<th>
Accept / Reject
</th>
<th>
Details
</th>
<th>
</th>
</tr>
#foreach (var item in Model.Requests)
{
#if (item.Type == "Register" && item.Institution.Status == "Pending") #*need one*#
{
<tr>
<td>
#Html.DisplayFor(m => item.Institution.Name)
</td>
<td>
#Html.DisplayFor(m => item.Date)
</td>
<td>
#Html.DisplayFor(m => item.Institution.Seats)
</td>
<td>
#Html.DisplayFor(m => item.ActualSeats)
</td>
<td>
#Html.DisplayFor(m => item.Seats)
</td>
<td>
<select id="selectedAnalyst_#item.Id" asp-for="selectedAnalyst" asp-items=" Model.AnalystList.ToSelectListItem(Model.selectedAnalyst)" class="form-control">
<option selected value="">--- Choose ---</option>
</select>
</td>
<td>
<a class="btn btn-info" asp-controller="Request" asp-action="ApproveRequest" asp-route-id="#item.Id"> accept </a>
<a class="btn btn-info" asp-controller="Request" asp-action="RejectRequest" asp-route-id="#item.Id"> Reject </a>
</td>
<td>
<button type="submit" class="btn btn-success anchorDetail" data-target="#modal-#item.Institution.Id" data-toggle="modal">
View Details
</button>
</td>
<td>
<div class="modal fade" id="modal-#item.Institution.Id" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog-centered modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-success text-light justify-content-center">
<h5 class="modal-title">Request Details</h5>
</div>
<div class="modal-body justify-content-center" id="MyModalContent">
#await Html.PartialAsync("_RequestDetails", item)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
}
</table>
}
else
{
<p>No Institutions Exists...</p>
}
</div>
</div>
#section scripts
{
<script>
function accept(id) {
var aid = $('#selectedAnalyst_' + id).val()
location.href = "/Request/ApproveRequest?id=" + id + "&Analystid=" + aid
}
var PostBackURL = '/Request/RequestDetails';
$(function () {
$(".anchorDetail").click(function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
$.ajax({
type: "GET",
url: PostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
cache: false,
datatype: "json",
success: function (data) {
$('#MyModalContent').html(data);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
</script>
}
<div class="modal fade" id="MyModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div id='MyModalContent'></div>
</div>

If you want to pass #item.id and $('#selectedAnalyst_' + id).val() to controller with form,you can do like this.Here is a demo worked(put form outside dropdownlist and button):
<form method="post"
asp-controller="Request"
asp-action="ApproveRequest"
asp-route-id="#item.Id">
<td>
<select id="selectedAnalyst_#item.Id" asp-for="selectedAnalyst" class="form-control">
<option selected value="">--- Choose ---</option>
<option selected value="1">1</option>
<option selected value="2">2</option>
<option selected value="3">3</option>
</select>
</td>
<td>
<button type="submit">Accept</button>
</td>
</form>
Controller(change Analystid to selectedAnalyst,so that you can bind asp-for="selectedAnalyst",and if you want to get string parameter,you can change it to string selectedAnalyst):
public IActionResult ApproveRequest(int id,string selectedAnalyst)
{
return Ok();
}
result:

Related

Not able to load details based on applied filters in ajax and laravel

I am new to Laravel and ajax and I am trying to apply Custom filters on Table data. I have followed this tutorial https://www.youtube.com/watch?v=XmUH049dk9I but unfortunately it's not working. I have used yajra data tables.
Here is my controller code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class CustomSearchController extends Controller
{
function index(Request $request)
{
if(request()->ajax())
{
if(!empty($request->Business_unit))
{
$data = DB::table('memberdetails')
->select('membersid','Role','Region','Orglevel1','Orglevel2')
->where('Business_unit',$request->Business_unit)
->get();
}
else
{
$data = DB:: table('memberdetails')
->select('membersid','Role','Region','Orglevel1','Orglevel2')
->get();
}
return datatables()->of($data)->make(true);
}
$Business_unit = DB::table('memberdetails')
->select('Business_unit')
->groupBy('Business_unit')
->orderBy('Business_unit', 'ASC')
->get();
return view('admin.members.test', compact('Business_unit'));
}
}
This is my view
#extends('layouts.admin')
#section('content')
<div class="row">
<div class="col">
<div class="form-group">
<select name="Business_unit" id="Business_unit" class="form-control">
<option value="">Business Unit</option>
#foreach($Business_unit as $Bu)
<option value="{{ $Bu->Business_unit }}">{{ $Bu->Business_unit}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<button class="btn btn-primary rounded" type="button" id="search" name="search">Apply</button>
</div>
<div class="form-group">
<button class="btn btn-primary rounded" type="button" id="reset" name="reset">Reset</button>
</div>
</div>
</div>
<div class="table-responsive">
<table id="members_data" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 10%">
Employee ID
</th>
<th style="width: 10%">
Role
</th>
<th style="width: 10%">
Region
</th>
<th style="width: 12%">
Org Level1
</th>
<th style="width: 12%">
Org Level2
</th>
</tr>
</thead>
</table>
#endsection
<script type="text/javascript">
$(document).ready(function(){
fill_datable();
function fill_datable(Business_unit = ''){
var datatable = $('members_data').DataTable({
processing: true,
ajax:{
url:{{ "route('CustomSearch.index')" }},
data:{ Business_unit:Business_unit }
},
columns: [
{
data: 'membersid',
name: 'membersid'
},
{
data: 'Role',
name: 'Role'
},
{
data: 'Region',
name: 'Region'
},
{
data: 'Orglevel1',
name: 'Orglevel1'
},
{
data: 'Orglevel2',
name: 'Orglevel2'
},
]
});
}
$('#search').click(function()
{
var Business_unit = $('#Business_unit').val();
if( Business_unit != '')
{
$('#members_data').DataTable().destroy();
fill_datable(Business_unit);
}
else
{
alert('Select Business Unit Filter');
}
});
$('#reset').click(function(){
$('#Business_unit').val();
$('#members_data').DataTable().destroy();
fill_datable();
});
});
</script>
and this is the route
Route::get('/test', [App\Http\Controllers\CustomSearchController::class, 'index'])->name('test');
Not sure what is missing... I am able to load the Business units in dropdown but the data is not loading and nor the filters are getting applied. Can someone help me out in this?

Angular UI Switch not retaining enabled when enabled

i'm a newbie here, hope you could help me with my problem, i am having trouble with retaining the enabled status of my angular ui switch... whenever i refresh the page, it reverts back to disabled . but when i check the database, i could it has updated the value and the selected setting name for the selected ui switch. i want to retain the enabled status of my angular ui switch whenever i enabled it
here is my javascript
(function () {
'use strict';
angular.module('mainApp')
.controller('AdminSettingsController', AdminSettingsController);
function AdminSettingsController(
$scope
,$location
,AdminSettingsService
,$routeParams
) {
$scope.updateSettings = updateSettings;
$scope.getList = getList;
$scope.companyId = $routeParams.companyId;
function updateSettings(key, newStatus) {
AdminSettingsService.saveSetting(newStatus, key, $scope.companyId).then(function (responseObj) {
let data = responseObj.data;
console.log(data.settings)
let success = data.success;
$scope.settings = data.settings;
return data.settings;
});
}
function getList(key){
AdminSettingsService.getSetting(key).then(function (response) {
let data = response.data;
console.log('hardyharhar');
let success = data.success
});
}
}
})();
here is my html
<side-nav active-tab="'admin'"></side-nav>
<head-bar></head-bar>
<div class="br-mainpanel">
<div class="br-pageheader pd-y-15 pd-l-20">
<nav class="breadcrumb pd-0 mg-0 tx-12">
<a class="breadcrumb-item" href="#!/home">Dashboard</a>
<span class="breadcrumb-item active">Admin Settings</span>
</nav>
</div>
<div class="pd-x-5 pd-sm-x-30 pd-t-20 pd-sm-t-2">
<div class="d-flex align-items-center ">
<i class="icon ion-settings tx-54" style="margin-right: 1px;"></i>
<div class="mg-l-20">
<h4 class="tx-18 tx-gray-800 mg-b-5" style="size: 50px; font-weight: bold">Admin Settings</h4>
<span class="mg-b-0">Settings for company.</span>
</div>
<div id="ch5" class="ht-60 tr-y-1"></div>
</div>
</div>
<div class="br-pagebody">
<div class="br-section-wrapper">
<div class="br-pagebody pd-x-20 pd-sm-x-30">
<div class="card bd-0 shadow-base">
<div class="table-responsive">
<table class="table table-striped table-bordered mg-b-0">
<thead>
<th style="width: 10%" class="text-center">Action</th>
<th style="width: 40%" class="text-center">Settings</th>
<th style="width: 10%" class="text-center">Status</th>
</thead>
<tbody>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReimbursementEnabled', reimbursementStatus)" id="state" name="state" ng-model="reimbursementStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4>Reimbursement</h4>
<p>Allows processor to access reimbursement {{ reimbursementStatus }}.</p>
</td>
<td>
<h4> <span class= "{{ reimbursementStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}">
{{ reimbursementStatus ? "Enabled" : "Disabled"}}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReportsEnabled', reportsEnabled)" id="state" name="state" ng-model="reportsEnabled" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Reports</h4>
<p>Allows processor to access reports.</p>
</td>
<td>
<h4> <span class="{{ reportsEnabled ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}" >
{{ reportsEnabled ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isAccountsEnabled', accountStatus)" id="state" name="state" ng-model="accountStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Accounts</h4>
<p>List of company accounts.</p>
</td>
<td>
<h4><span class="{{ accountStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}" >
{{ accountStatus ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReimbursementRequestLimitEnabled', requestStatus)" id="state" name="state" ng-model="requestStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Reimbursement Request Limit</h4>
<p>Sets the reimbursement request limit per year.</p>
</td>
<td>
<h4><span class="{{ requestStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}">
{{ requestStatus ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<foot-bar></foot-bar>
</div>
</div>
and here is my api controller
namespace App\Http\Controllers\Api;
use App\Criteria\LimitOffsetCriteria;
use App\Http\Controllers\Controller;
use App\Models\AdminSettings;
use App\Models\AccountSettings;
use App\Models\Account;
use App\Repositories\AccountRepositoryEloquent;
use App\Repositories\AdminSettingsRepositoryEloquent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AdminSettingApiController extends Controller
{
private $adminSettingsRepository;
private $accountRepository;
public function __construct(
AdminSettingsRepositoryEloquent $adminSettingsRepo
,AccountRepositoryEloquent $accountRepo
)
{
$this->adminSettingsRepository = $adminSettingsRepo;
$this->accountRepository = $accountRepo;
}
public function saveSetting(Request $request) {
$newStatus = $request->input('newStatus');
$key = $request->input('key');
$companyId = $request->input('companyId');
$result = array(
'success' => false
);
$keyExist = $this->adminSettingsRepository->findByField('setting_name', $key)->first();
log::debug('thisisKeyExist.......................'.json_encode($keyExist));
$newStatusData = [
'setting_name' => $key,
'status' => $newStatus,
'company_id' => $companyId
];
try {
DB::beginTransaction();
if (!$keyExist) {
$newStatus = AdminSettings::create($newStatusData);
}
else {
$updateQuery = AdminSettings::where('setting_name', '=', $key);
$updateQuery->update($newStatusData);
}
$result['success'] = true;
$result['settings'] = $newStatusData;
DB::commit();
} catch (Exception $e) {
Log::error($e);
$result['success'] = false;
$result['messages'] = ['Server has encountered an unexpected error.'];
}
return $result;
}
public function list(Request $request){
$key = $request->input('key');
$result = array(
'success' => false
);
$keySetting = $this->adminSettingsRepository->findByField('setting_name', $key)->first();
$keyList = [];
try {
DB::beginTransaction();
$keyList = $this->adminSettingsRepository::where('status', '=', 1, 'setting_name')->get();
Log::debug('thisIsPrimarykey...................'.json_encode($keyList));
$result['key'] = $key;
$result['success'] = true;
DB::commit();
}
catch (\Exception $e){
Log::error($e);
$result['success'] = false;
}
}
}
hope you could help me thanks a lot! :)

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

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)

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

Categories