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);
Related
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);
}
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
how to get the name of select tag and use to if condition here is my code:
#{
var size="";
if(Request.Form["cboSize"] == "Extra Small (XS)"){
size = "Extra Small (XS)";
}
...
}
<select name="cboSize">
<option value="xs">Extra Small (XS)</option>
<option value="s">Small (S)</option>
<option value="m">Medium (M)</option>
<option value="l">Large (L)</option>
<option value="xl">Extra Large (XL)</option>
</select>
You need to wrap your select node in a form to get its value from Request.Form["cboSize"]:
<form method="POST">
<select name="cboSize">
<option value="xs">Extra Small (XS)</option>
<option value="s">Small (S)</option>
<option value="m">Medium (M)</option>
<option value="l">Large (L)</option>
<option value="xl">Extra Large (XL)</option>
</select>
<input type="submit" />
</form>
Then in your code:
public async Task<IActionResult> OnPostAsync()
{
var size = Request.Form["cboSize"];
//do something with it asyncronously
return RedirectToPage($"/Details/{size}");
}
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>
}
My JSP snippet is as follows:
<form:select path="rules[${counter.index}].assignedTo.assignedToName">
<form:options items="${assignmentRulesForm.assignedToList}"
itemLabel="assignedToName"
itemValue="assignedToName"/>
</form:select>
The assignedTo property refers to this object:
public class AssignmentDTO {
private String assignedToName;
// No other members
assignedToList then is a List<AssignmentDTO>
Really, what I want to happen is for the drop-down to contain all entries in the assignedToList, but to select the value associated with rule[i].assignedto.assignedToName
Presently, what I am seeing is that it does not perform the selection part, and the first item in the drop-down is displayed.
Any help is appreciated.
Thanks
This should work for you, the path is not the name but the assignedTo:
<form:select path="rules[${counter.index}].assignedTo">
<form:options items="${assignmentRulesForm.assignedToList}"
itemLabel="assignedToName"
itemValue="assignedToName"/>
</form:select>
If you have implemented a .equals for your assignedTo, it should just work.
<html>
<head>
<script>
function show() {
var op= window.document.getElementById('select');
var selItem= op.options[op.selectedIndex].value;
if(selItem=="Others") {
document.getElementById('text').style.visibility = 'visible';
}
else {
document.getElementById('text').style.visibility = 'hidden';
}
}
</script>
</head>
<select id="select" onchange="show();">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="Others">Others</option>
</select>
<br>
<input type="text" id="text" style="visibility:hidden">
</html>