MVC4 No update on selchange DropDownList Postback - asp.net-mvc-4

After I have changed selected item in my DropDownList everything works fine. But the view doesnt show the newly selected item (value) in the view.
In my code there is #Model.Name What is wrong? I have already spent do many hours on this problem!
My controller looks like this:
//
// GET: /Province/
public ActionResult Test()
{
ModelState.Clear();
var items = _ProvinceService.GetAll();
ViewBag.Lista = new SelectList(items, "Id", "Name", -1);
var province = _LandskapService.FindByName("xyz");
return View("Test", province);
}
// POST /Province/Test
[HttpPost]
public ActionResult Test(int provinceId)
{
if (ModelState.IsValid)
{
ModelState.Clear();
var model = _ProvinceService.GetAll();
var province = _ProvinceService.FindById(provinceId);
ViewBag.Lista = new SelectList(model, "Id", "Name", province.Id);
return View("Test", province);
}
else
{
return View();
}
}
And here is the view:
#Html.DropDownList("dropDownList3", (SelectList)ViewBag.Lista, "-- select province", new { onchange = "UpdateProvince()" })
<table style="border-collapse:collapse">
<tr>
<th style="width:200px">Name</th>
</tr>
<tr>
<td> #Model.Name </td> Here is the problem: #Model.Name is correct but the view dont show it. Old value is displayed. But debugger shows right value (the selected value).
</tr>
function UpdateProvince() {
alert($('#dropDownList3').val());
var SelCat = $("#dropDownList3").val();
var text = $("#dropDownList3 option:selected").text();
var value = $("#dropDownList3 option:selected").val();
if (SelCat != 0) {
var url = '#Url.Action("Test", "Province")';
// $.get(url, {provinceId : value});
$.post(url, { provinceId: value });
}
}

Related

ASP.NET MVC: drop down list display everything and also display alone

I currently display each category individually, but I want to make it possible to view them all together.
Here in the screenshot, I show each category separately, but I want to add another All option that will show me all the animals in all the categories
My repository:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
var animal = _context.Animals
.Include(a => a.Category)
.Where(c => c.Category!.CategoryId == id);
return await animal.ToListAsync();
}
public DbSet<Category> GetCategories()
{
var category = _context.Categories;
return category;
}
My controller:
// Displays the animals by category using the Selectlist
public async Task<IActionResult> Commands(int id = 1)
{
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
My view:
#model IList<PetShop.Data.Models.Animal>
<label>Please select a category:</label>
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect"></select>
<table id="Table">
<thead>
<tr>
<th><label asp-for="#Model[0].PhotoUrl"></label></th>
<th><label asp-for="#Model[0].Name"></label></th>
<th><label asp-for="#Model[0].Category.Name"></label></th>
<th><label asp-for="#Model[0].Description"></label></th>
<th><label asp-for="#Model[0].BirthDate"></label></th>
<th>Edit Animal</th>
<th>Delete Animal</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model!) {
<tr>
<td><img src="~/Images/#item.PhotoUrl" id="ManagerImage"></td>
<td>#item.Name</td>
<td>#item.Category!.Name</td>
<td>#item.Description</td>
<td>#Html.DisplayFor(model => item.BirthDate)</td>
<td><a asp-action="EditAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Edit" id="DesignButton"></a></td>
<td><a asp-action="DeleteAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Delete" id="DesignButton"></a></td>
</tr>
}
</tbody>
</table>
image:
One way is that you can change your code in repository like below:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
List<Animal> data= new List<Animal>();
var animal = _context.Animal
.Include(a => a.Category);
if (id != 0)
{
data= await animal.Where(c => c.Category!.CategoryId == id).ToListAsync();
}
else
{
data= await animal.ToListAsync();
}
return data;
}
Another way is that you can change your action code like below:
public async Task<IActionResult> Commands(int id = 1)
{
//add this condition
//if id=0, return all the animals with all the categories
if(id==0)
{
return View(_context.Animal.Include(a => a.Category).ToList());
}
//keep the same.....
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);;
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
Then change your view like below:
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect">
<option value="0">ALL</option> //add this option
</select>
You could conditional add the where clause in your repository...
var animal = _context.Animals
.Include(a => a.Category);
if(id != 0)
{
animal.Where(c => c.Category!.CategoryId == id);
}
return await animal.ToListAsync();

HTML Table search on the third column using JavaScript

I am trying to search any employee status exist with IsProtected in the tabl empTable. if any row exist , then the variable ProtectedIsfound must be true
<table id="empTable" >
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
for (i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> // it is boolean in model
</tr>
}
</table>
<script>
var ProtectedIsfound = True // if any record exist with the value is Protected in the column status in the table empTable
</script>
I am trying to search any employee status exist with IsProtected in
the tabl empTable. if any row exist , then the variable
ProtectedIsfound must be true
Do you mean for each row, if the IsProtected is true, the ProtectedIsFound must be true? If that is the case, please refer to the following methods:
Using JavaScript or JQuery method: Loop through the table rows and cells and check if the IsProtected is true, then, based on the result to change the ProtectedIsFound value.
#*JQuery reference*#
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
var ProtectedIsfound = false // default value.
//JavaScript method:
document.addEventListener("DOMContentLoaded", function (event) {
//loop through the tr and td, then based on the IsProtected value to change the ProtectedIsFound value.
var trlist = document.getElementById("empTable").getElementsByTagName("tr");
for (var i = 1; i < trlist.length; i++) {
if (trlist[i].getElementsByTagName("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
break;
}
}
console.log(ProtectedIsfound);
});
//JQuery script
$(function () {
$("#empTable").find("tr:not(:first-child)").each(function (index, item) {
if ($(item).find("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
return false;
}
});
console.log(ProtectedIsfound);
});
</script>
Using Where and Select statement, code as below:
<script type="text/javascript">
var ProtectedIsfound = #Model.attendanceLogList.Where(c => c.IsProtected ==true).Select(c=>c).ToList().Count > 0 ? true : false;
console.log(ProtectedIsfound);
</script>
The Html page elements as below (Asp.net core Razor page application):
#page
#model RazorWebApplication5.Pages.HtmlTableModel
#{
}
<table id="empTable">
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
#for (var i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> #*// it is boolean in model*#
</tr>
}
</table>
.cshtml.cs file:
public class HtmlTableModel : PageModel
{
public List<AttendanceLog> attendanceLogList { get; set; }
public void OnGet()
{
//initial data
attendanceLogList = new List<AttendanceLog>()
{
new AttendanceLog(){ EmployeeName="Tom", Designation="A", IsProtected=false},
new AttendanceLog(){ EmployeeName="Jack", Designation="B", IsProtected=false},
new AttendanceLog(){ EmployeeName="Lucy", Designation="CC", IsProtected=true},
new AttendanceLog(){ EmployeeName="Daive", Designation="D", IsProtected=false},
new AttendanceLog(){ EmployeeName="Hanke", Designation="E", IsProtected=false}
};
}
}
public class AttendanceLog
{
public string EmployeeName { get; set; }
public string Designation { get; set; }
public bool IsProtected { get; set; }
}
Test result:
Change the for loop into:
"for (i = 0; i <= Model.attendanceLogList.Count; i++)", it should count up to the total number of the List.
Not sure what library you're using in the script, but instead of:
var ProtectedIsfound = True, it should state
You need a dedicated class name to the so you can refer it in the script
"bool ProtectedIsFound:"
It should be set to true by default.
foreach(emp in Model.attendanceLogList){
if (emp.IsProtected){
{here you will need to append the value in the Status column}
return true; }
else
return;
}

X.PagedList, manual Paging and a pre-existing webapi for data only advance 1 record at a time

Setting up a PagedList in .netcore against a webapi that already exists.
The webapi allows me to call data using a 2 parameters, a FROM and a TAKE. I've implemented X.PagedList and it appears to work except for how it/I calculate the actual Page..
Using the code at X.PagedList, I implemented the Manual Paging. The issue is that when I click on a page number, my TAKE only takes 1 new record, as opposed to the NEXT 10.
On the first load, my api call looks like this
/api/v1/Institutions?from=0&take=10
The Page 2 call looks like
/api/v1/Institutions?from=1&take=10
Obviously the 1 should be 11 i think in this case
PagedResults Class
public class PagedResults<T> : List<T>
{
public List<T> Results { get; set; }
public string Search { get; set; }
public bool Empty { get; set; }
}
My Controller
public IActionResult PagedList(int? page)
{
ViewData["Title"] = Title;
ViewData["PageTitle"] = Title + " List";
var pageIndex = (page ?? 1) - 1;
var pageSize = 10;
//Perform API Call
var response = GetList(pageIndex, pageSize);
//Returns List<Institution>
var Institutions = response.Data;
//Returns 200, which is the total from the Headers
string total = response.Headers.Where(x => x.Name == "total").Select(x => x.Value).FirstOrDefault().ToString();
var PagedList = new StaticPagedList<Institution>(Institutions, pageIndex + 1, pageSize, Convert.ToInt32(total));
var model = new InstitutionViewModel
{
CurrentUser = CurrentUser //From BaseController
};
string view = string.Format("~/views/Portal/{0}/List.cshtml", Title);
ViewData["PagedList"] = PagedList;
return View(view, model);
}
GetList()
#region Helpers
public static IRestResponse<List<Models.Institution>> GetList(int from, int take)
{
//this create /api/v1/institutions?from=0&Take=10
string ActionPath = string.Format("Institutions");
var client = new RestClient(Connect.url);
var request = new RestRequest(ActionPath, Method.GET);
request.AddParameter("from", from, ParameterType.QueryString);
request.AddParameter("take", take, ParameterType.QueryString);
var result = client.Execute<List<Models.Institution>>(request);
return result;
}
#endregion
My View
#using X.PagedList.Mvc.Core;
#using X.PagedList;
#foreach (var item in ViewBag.PagedList)
{
<tr>
<td>#item.id</td>
<td>#item.name</td>
</tr>
}
#Html.PagedListPager((IPagedList)ViewBag.PagedList, page => Url.Action("PagedList", new { page }))
Here is a simple workaround like below:
1.View:
#{
ViewBag.Title = "Product Listing";
var pagedList = (IPagedList)ViewBag.PageList;
}
#using X.PagedList.Mvc.Core; #*import this so we get our HTML Helper*#
#using X.PagedList; #*import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)*#
#using X.PagedList.Mvc.Common
#using X.PagedList.Mvc.Core.Fluent
<ul>
#foreach (var name in ViewBag.PageList)
{
<li>#name</li>
}
</ul>
#Html.PagedListPager(pagedList, page => Url.Action("Index", new { page }))
2.Controller:
[HttpGet]
public IActionResult Index(int page = 1)
{
ViewBag.PageList = GetPagedNames(page);
return View();
}
protected IPagedList<string> GetPagedNames(int? page)
{
// return a 404 if user browses to before the first page
if (page.HasValue && page < 1)
return null;
// retrieve list from database/wherever
var listUnpaged = new List<string> { "a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee", "aaa", "bbb", "ccc" ,"ddd","eee","fff","ggg","1","s","f","sd","dsfds"};
// page the list
const int pageSize = 10;
var listPaged = listUnpaged.ToPagedList(page ?? 1, pageSize);
// return a 404 if user browses to pages beyond last page. special case first page if no items exist
if (listPaged.PageNumber != 1 && page.HasValue && page > listPaged.PageCount)
return null;
return listPaged;
}

How to show different text according to a bool value from the SQL database?

Why in the view page, it shows all the rows "Not active currently" with this following code?
<td>
#{
if (item.LeadEngineers.All(n => n.Active == false))
{
#: Not active currently
}
var y = item.LeadEngineers.Where(n => n.Active == true).ToList();
if (y.Count() > 0)
{
#: Currently active
}
}
</td>
I want to check if the item's value in another table LeadEngineers is true or false, to show the item is currently active or not.
The item has many records in the table LeadEngineers, I want to check if all the records/rows have Active=False, then show "not active", if there's one row (at least one) has Active=true, then show "active now".
The definition of the item is in the view Model LeadIndexData:
public class LeadIndexData
{
//to show each item's full name
public IEnumerable<WebUser> WebUsers { get; set; }
//to show each item's assigned techniques
public IEnumerable<Technique> Techniques { get; set; }
//to show each item's supervised employees
public IEnumerable<EmployeeTech> EmployeeTechs { get; set; }
//to show if it's active or not
public IEnumerable<LeadEngineer> Leads { get; set; }
}
My Controller:
public ActionResult Index(int? id, int? techId)
{
var viewModel = new LeadIndexData();
var query = (from b in db.LeadEngineers
join a in db.WebUsers
on b.User_ID equals a.User_ID
where a.Active == true
select new
{
User_ID = b.User_ID,
User_FirstName = a.User_FirstName,
User_Surname = a.User_Surname
}).AsEnumerable().Select(x => new WebUser
{
User_ID = (int)x.User_ID,
User_FirstName = x.User_FirstName,
User_Surname = x.User_Surname
}).Distinct().ToList();
//put the query results into the list of leads
var engineers = query.AsEnumerable();
//use HashSet to hold a set of lead webusers
HashSet<WebUser> vme = new HashSet<WebUser>();
//access each item in the leads list and assign the lead webuser's details to each
foreach (var wu in engineers)
{
var w = new WebUser { User_ID = wu.User_ID, User_Surname = wu.User_FullName };
if (!(vme.Any(x => x.User_ID == wu.User_ID)))
{
vme.Add(w); //add the lead webuser details to the hashSet
}
}
//put the webusers details vme in the leadengineer viewmodel
viewModel.WebUsers = vme.ToList();
.....
}
My Index View page:
#model Version0.Models.LeadIndexData
....
....
#foreach (var item in Model.WebUsers)
{
string selectedRow = "";
if (item.User_ID == ViewBag.userId)
{
selectedRow = "success";
}
<tr class="#selectedRow" valign="top">
<td>
#Html.DisplayFor(modelItem => item.User_Surname)
</td>
<td>
#Html.DisplayFor(modelItem => item.User_FirstName)
</td>
<td>
#{
if (item.LeadEngineers.Any(n => n.Active == true))
{
#: Currently active
}
else
{
#: Not active currently
}
}
</td>
....
</table>
Here you are:
<td>
#{
if (item.LeadEngineers.Any(n => n.Active == true))
{
#: Currently active
}
else
{
#: Not active currently
}
}
</td>

MVC4 Dropdownlist

I need to pass values from three dropdownlists to the controller when user selects some value from any one of the dropdownlist.i tried like this but the value from only the dropdown selected is passed others are null values ,any help would be appreciated.
VIEW
##using (Html.BeginForm("GetFilterValues","Home",FormMethod.gET))
{
#Html.DropDownList("FClass", ViewBag.Market as SelectList, new { id = "Market" , onchange = "$(this).parents('form').submit();" })
}
#using (Html.BeginForm("GetFilterValues","Home",FormMethod.Get))
{
#Html.DropDownList("FClass", ViewBag.Class as SelectList, new { id = "FClass" , onchange = "$(this).parents('form').submit();" })
}
</td>
<td>
#Html.Label("Status")
</td>
<td>
#using (Html.BeginForm("GetFilterValues","Home",FormMethod.Get))
{
#Html.DropDownList("Status", ViewBag.Status as SelectList, new { id = "Status" , onchange = "$(this).parents('form').submit();" })
}
CONTROLLER
[HttpgET]
public void GetFilterValues()
{
string market = this.Request.Form.Get("Market");
string fclass = this.Request.Form.Get("FClass");
string status = this.Request.Form.Get("Status");
}
Try a single form trough a POST and pull the values by name using a FormCollection like this...
View:
#using (Html.BeginForm("GetFilterValues","Home", FormMethod.Post))
{
#Html.DropDownList("nameMarket", ViewBag.Market as SelectList, new { id = "Market" , onchange = "$(this).parents('form').submit();" })
#Html.DropDownList("nameClass", ViewBag.Class as SelectList, new { id = "FClass" , onchange = "$(this).parents('form').submit();" })
#Html.DropDownList("nameStatus", ViewBag.Status as SelectList, new { id = "Status" , onchange = "$(this).parents('form').submit();" })
}
Controller:
[HttpPost]
public void GetFilterValues(FormCollection collection) {
string market = Convert.ToString(collection["nameMarket"]);
string fclass = Convert.ToString(collection["nameClass"]);
string status = Convert.ToString(collection["nameStatus"]);
}