How to put just distinct values into select control MVC ASP.NET? - asp.net

This is my index view. I tried with ViewBag but it doesn't work, maybe because I want to get values from foreign key. I am new to ASP.NET.
<form id="forma" action="/InspekcijskeKontrole/VratiKontrole" method="get">
<div class="form-group">
<label for="Select1">Odaberite inspekcijsko tijelo:</label>
<select name="Select1" id="Select1" class="form-control" onchange="sacuvaj()">
<option value="-1">Selektujte inspekcijsko tijelo:</option>
#foreach (var i in ViewBag.Select1) {
<option value="#i.Value">#i.Text</option>
}
</select><br />
<label for="Select2">Odaberite vremenski period kontrole:</label>
<select name="Select2" id="Select2" class="form-control" onchange="sacuvaj1()">
<option value="-1">Selektujte vremenski period kontrole:</option>
#foreach(var i in Model)
{
<option value="#i.DatumInspekcijskeKontrole.ToString("dd.MM.yyyy")">#i.DatumInspekcijskeKontrole.ToString("dd.MM.yyyy")</option>
}
</select>
</div>
This is my controller
public ActionResult VratiKontrole(int Select1, string Select2)
{
IEnumerable<string> tijelaNaziv = db.InspekcijskaKontrolas.OrderBy(i => i.InspekcijskoTijelo.NazivInspekcijskogTijela).Select(i => i.InspekcijskoTijelo.NazivInspekcijskogTijela).Distinct();
ViewBag.Select1 = new SelectList(tijelaNaziv);
IQueryable<InspekcijskaKontrola> listaKontrola = db.InspekcijskaKontrolas.Select(i => i);
if (!string.IsNullOrEmpty(Select1.ToString())&&!string.IsNullOrEmpty(Select2.ToString()))
{
string[] parts = Select2.Split('.');
DateTime datum = new DateTime(int.Parse(parts[2]), int.Parse(parts[1]), int.Parse(parts[0]));
listaKontrola = listaKontrola.Where(l => l.InspekcijskoTijeloId == Select1).Where(l => l.DatumInspekcijskeKontrole == datum).Select(l => l);
}
return View(listaKontrola.ToList());
}

(Posted on behalf of the OP).
This is solved. I just put into view:
#foreach (var i in Model.Select(i=>i.InspekcijskoTijelo).Distinct()) {
<option value="#i.InspekcijskoTijeloId">#i.NazivInspekcijskogTijela</option>
}

Related

Error when Search() Action Method returns Index View()

I have a Search Form which goes to my Search() action method within my Home Controller. and returns View("Index")
Search() method:
public IActionResult Search(SearchQuery FormData)
{
List<Flight> flights = new List<Flight>();
flights = (from flight in _context.Flights
where flight.FlightDateTime.Date == FormData.PreferredFlightTime.Date
&& flight.ArrivalAirportId == FormData.ArrivalAirportId
&& flight.DepartureAirportId == FormData.DepartureAirportId
select flight).ToList();
ViewBag.FlightSearchResults = flights;
return View("Index");
}
Upon the initial load of the homepage it works fine when loading my Index() method and returning the view.
public IActionResult Index()
{
HomeViewModel mymodel = new HomeViewModel();
mymodel.Airports = GetAirports();
return View(mymodel);
}
However once the search form is submitted and the Search() action method is called, when the method returns return View("Index"); the page will not load due System.NullReferenceException: 'Object reference not set to an instance of an object.'
The above exception is thrown when it reaches #foreach (Airport airport in Model.Airports)
Search form:
#using FlightBooker;
#model FlightBooker.Models.HomeViewModel;
<form asp-controller="Home" asp-action="Search" method="post">
<div class="form-group">
<label for="fromAirport">Flying from:</label>
<select name=" {DepartureAirportId" class="form-control">
#foreach (Airport airport in Model.Airports)
{
<option value="#airport.AirportId">#airport.AirportCode</option>
}
</select>
<div class="form-group">
<label for="toAirport">Flying to:</label>
<select name="ArrivalAirportId" class="form-control">
#foreach (Airport airport in Model.Airports)
{
<option value="#airport.AirportId">#airport.AirportCode</option>
}
</select>
</div>
<label for="fromAirport">Departure Date:</label>
<br />
<input type="date" / id="date" name="PreferredFlightTime">
<br />
<label for="fromAirport">No. passengers:</label>
<select class="form-control" name="TotalPassengers">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<button type="submit" class="btn btn-primary mt-3">Search Flights</button>
</div>
</form>
Comment from Codecaster above solved this. I updated my Search() action method passing the model to the Index view and repeating the code in my index method.
Updated Search() action method:
public IActionResult Search(SearchQuery FormData)
{
List<Flight> flights = new List<Flight>();
flights = (from flight in _context.Flights
where flight.FlightDateTime.Date == FormData.PreferredFlightTime.Date
&& flight.ArrivalAirportId == FormData.ArrivalAirportId
&& flight.DepartureAirportId == FormData.DepartureAirportId
select flight).ToList();
ViewBag.FlightSearchResults = flights;
HomeViewModel mymodel = new HomeViewModel();
mymodel.Airports = GetAirports();
return View("Index", mymodel);
}

Use drop down result to filter another dropdown C# MVC

I am trying to update a drop down based on the users selection in the first drop down. I found this SO post on the topic, but Im not quite sure how to add the jquery to filter values to my Razor view. Can someone point me in the right direction?
My view so far:
#using System.Security.Claims;
#model UpdateClaimFormModel;
<h2>UpdateClaimView</h2>
#using (#Html.BeginForm())
{
<select name="emailcheese">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy">
<option selected disabled>Select Claim:</option>
#foreach (var i in Model.UserClaims)
{
<option>#i.Type.ToString()</option>
}
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
My Goal:
Select User [bob, bill, jim]
Select Claim: If user bob:[1,2,3], If user bill:[1,4,8], If user him:[4,5,6]
so simpley you can do something like this
#using (#Html.BeginForm())
{
<select name="emailcheese" id="selectUserNames">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy" id="selectAuthPolicy">
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
now in the script part
$(function(){
var userClaims = #Html.Raw(Json.Encode(Model.UserClaims));
$(document).on('change','#selectUserNames'function(){
var selectedVal = $(this).val();
if(selectedVal == 'bob')
{
var html ='<option selected disabled>Select Claim:</option>';
for(var i=1;i<userClaims.length;++i)
{
if(i==1||i==2||i==3)
{
html=html+'<option>'+userClaims[i].Type+'</option>';
}
}
$('#selectAuthPolicy').html(html);
}
})
})
this is just a basic dea of how you can achieve this i just tried for bob there are many other ways to immplement ths

cascading dropdown angularjs mvc

i am getting null values
$scope.GetDepartment = function (Department) {
$http.get('/Official/GetDepartment?Department=' + Department).then(function (data) {
console.log(data);
$scope.department= data.data;
});
};
Html
<select ng-model="empModel.division" id="" name="Division" class="form-control"
ng-click = "GetDepartment(empModel.division)"
ng-change = "GetDepartment(empModel.division)"
ng-options="c.division as c.division for c in division" >
<option selected="selected">Select</option>
</select>
<select ng-model="empModel.department" id="" name="Department" class="form-control"
ng-options="d.department as d.department for d in department">
<option></option>
</select>
When i select divison i am not getting anything in department dropdown
Controller
public JsonResult GetDepartment(string Department)
{
var department = db.Depts.Where(x => x.Department == Department).
GroupBy(x => x.Department).
Select(x => x.FirstOrDefault()).
OrderBy(x => x.Department).ToList();
return Json(department);
}
Your angular part for retrieve division data
function GetDesignation(input) {
$http.get('/Official/GetDesignation?designation='+input).then(function (data) {
console.log(data);
$scope.designation = data.data;
});
};
change in HTML using ng-change directive there
<select ng-model="empModel.division" id="" name="Division" class="form-control" ng-change = "GetDesignation(empModel.division)"
ng-options="c.division as c.division for c in division" >
<option></option>
</select>
New HTML tag for load Designation data in dropdown
<select ng-model="empModel.designation" id="" name="Designation" class="form-control"
ng-options="c.designation as c.designation for c in designation" >
<option></option>
</select>

how to get the selected value from a drop down list and transfer it to a viewbag

View
...Some Codes...
<select class="form-control" style = "width:400px">
<option selected> select issue type </option>
#foreach( var item in Model._issueList)
{
<option>#item.issueName</option>
}
</select>
...Some Codes...
Output of my dropdown
dropDown: issue_one, issue_two, issue_three
Now I want to choose my issue_three in my drop down and save it in a Viewbag.select, want should be the proper code so that I can transfer the issue_three to my Viewbag.select
TEST
...foreach code...
Viewbag.select = ????
View
<select class="form-control" style = "width:400px">
<option selected> Select Company Name </option>
#foreach (var item in Model._issueList)
{
<option id="issueSelect" onclick="transferIssue('#item.issueNo')">#item.issueName</option>
}
</select>
#Html.HiddenFor( m => m.variable,new { #class = "form-control", style = "width:400px", #id = "issue" })
...Some codes...
<button type ="submit" id='submit_button'>Submit</button>
SCRIPT Use JQUERY
function transferIssue(x){ $('#issue')val(); }
jQuery(document).on('click', '#submit_button', function (ev) {
ev.preventDefault();
var _issue = jQuery('#issue').val();
var _url = '#Url.Action("Jobs")' + '?value='+ _issue;
window.location.href = _url;
});

How to implement sort function in ASP.NET MVC

Now I am creating application using MVC Music Store tutorial. I want to implement sort function. I got stuck in implementation of Post Browse action.
Browse.cshtml
#model Overstock.Models.Category
#{
ViewBag.Title = "Browse Albums";
}
<div class="product">
<h3><em>#Model.Name</em> Products</h3>
<form action="/Store/Browse" method="POST">
Sort
<select id="Category" name="Category">
<option value="All">All</option>
<option value="Electronics">Electronics</option>
<option value="Sports">Sports</option>
<option value="Watches">Watches</option>
<option value="Office">Office</option>
<option value="Beauty">Beauty</option>
</select>
products by
<select id="SortType" name="SortType">
<option selected="selected" value="Name">Name</option>
<option value="Price">Price</option>
</select>
in
<select id="OrderBy" name="OrderBy">
<option selected="selected" value="Ascending">Ascending</option>
<option value="Descending">Descending</option>
</select>
order
<input type="submit" value="Set" />
</form>
<ul id="product-list">
#foreach (var product in Model.Products)
{
<li id="product">
<a href="#Url.Action("Details", new { id = product.ProductId })">
<img id="image" alt="#product.Title" src="#product.PictureUrl" />
<span>#product.Title</span>
</a>
</li>
}
</ul>
</div>
StoreController.cs
// GET: /Store/Browse
public ActionResult Browse(string category)
{
var varCategory = MyDB.Categories.Include("Products").Single(c=> c.Name==category);
return View(varCategory);
}
[HttpPost]
public ActionResult Browse(string Category, string SortType, string OrderBy)
{
//What should I put here?
return View();
}
What should I write in Browse Post action? Please help.
Using OrderBy and OrderByDesceding for example:
if(SortType == "Name") && (OrderBy == "Ascending")
MyDB.Categories.Where(x => x.Name == Category).OrderBy(x => x.Name);

Resources