ASP.NET MVC Search with dropdownlist in layout page - asp.net-mvc

I am stuck with very common problem, in my application I want to put search-navbar which will be available in every page.
I mean search with query to write and dropdownlist with category of item to search.
Because I want to have acces in every page, I implemented it in Layout page like below:
<div class="col-xs-10 search-field">
#Html.Editor(" ", new {htmlAttributes = new {#class = "search-input", #id = "searchQuery", #placeholder = ResourcesPolish.Search_WhatAreYouLookingFor}})
</div>
<div class="col-xs-4 category-field">
#Html.DropDownList(" ",
new SelectList(new[]
{
new SelectListItem {Value = "1", Text = "Elektronika"},
new SelectListItem {Value = "2", Text = "Moda i uroda"},
new SelectListItem {Value = "3", Text = "Dom i zdrowie"},
new SelectListItem {Value = "4", Text = "Dziecko"},
new SelectListItem {Value = "5", Text = "Kultura i rozrywka"},
new SelectListItem {Value = "6", Text = "Elektronika"},
new SelectListItem {Value = "7", Text = "Sport i wypoczynek"},
new SelectListItem {Value = "8", Text = "Motoryzacja"},
new SelectListItem { Value = "9", Text = "Kolekcje i sztuka"},
new SelectListItem {Value = "10", Text = "Firma"},
new SelectListItem {Value = "11", Text = "Inne"},
}, "Value", "Text"), "wszystkie działy", new { #class = "category-input", #id = "category" })
</div>
<div class="col-xs-1 search-button" onclick="search()">
</div>
Then, I have javascript which take value, that is selected:
function search() {
var categoryId = $('#category').val();
var query = $('#searchQuery').val();
if (query) {
window.location.href = '#Url.Action("SearchItem","Item")?query=' + query + '&categoryId=' + categoryId;
}
}
It work's fine, but all categories are hardcode'd, and maybe better solution is to read them from Db, because admin may change part of them? But I haven't got any way to do this via Layout page (I mean to pass them via model), so I don't know, is there any better solution for stuffs like that?
This is the same situation like at ebay.com, always at the top of the page there should be search-area with dropdown for categories.
Any ideas?

One solution is to create a controller for your navbars, like this:
public class NavbarController : Controller
{
public ActionResult Categories()
{
// you might want to return this from database, of course
var model = new SelectList(new[]
{
new SelectListItem {Value = "1", Text = "Elektronika"},
new SelectListItem {Value = "2", Text = "Moda i uroda"},
new SelectListItem {Value = "3", Text = "Dom i zdrowie"},
new SelectListItem {Value = "4", Text = "Dziecko"},
new SelectListItem {Value = "5", Text = "Kultura i rozrywka"},
new SelectListItem {Value = "6", Text = "Elektronika"},
new SelectListItem {Value = "7", Text = "Sport i wypoczynek"},
new SelectListItem {Value = "8", Text = "Motoryzacja"},
new SelectListItem { Value = "9", Text = "Kolekcje i sztuka"},
new SelectListItem {Value = "10", Text = "Firma"},
new SelectListItem {Value = "11", Text = "Inne"},
}, "Value", "Text");
return View(model);
}
}
Then a separate view called Categories.cshtml inside a Navbar folder, which would look like this:
#model SelectList
#{
Layout = null;
}
<div class="col-xs-10 search-field">
#Html.Editor(" ", new {htmlAttributes = new {#class = "search-input", #id = "searchQuery", #placeholder = ResourcesPolish.Search_WhatAreYouLookingFor}})
</div>
<div class="col-xs-4 category-field">
#Html.DropDownList(" ", Model, "wszystkie działy", new { #class = "category-input", #id = "category" })
</div>
<div class="col-xs-1 search-button" onclick="search()">
</div>
In your layout, you replace all that html with this:
#Html.Action("Categories", "Navbar");
Actually, I wouldn't use a SelectList as a model, it's just to show how it could work. You might want to create a CategoriesViewModel holding the SelectList, or an IEnumerable<CategoryViewModel> and create the SelectList inside your view, by using your model.

I'm not sure that it's right way, but also you can change your _Layout.cshtml like that:
#using D.Models//namespace where your database described
#{ db a = new db();
SelectList list = new SelectList(a.Table/*table what you need*/, "value", "name");
}
and then:
<div class="col-xs-4 category-field">
#Html.DropDownList(" ",list, "wszystkie działy", new { #class = "category-input", #id = "category" })
</div>

Related

Bind dropdown list with comma separated value for an item in mvc

I want to bind an html dropdown list with model data in such a way that “PWD-SUR” will display by default when “Account” = SBEN or SPPY or SPLF or SWOL
<div class="border col-md-2">
#Html.DropDownListFor(model => model.Account, new SelectList(new List<SelectListItem>
{ new SelectListItem { Text = "PWD-SUR", Value = "SBEN, SPPY, SPLF, SWOL"},
new SelectListItem { Text = "LOAN", Value = "LNPR"},
new SelectListItem { Text = "LN PYMT", Value = "LNIN"},
new SelectListItem { Text = "PREM", Value = "PREM"}
}, "Value", "Text"),"----", new {#id="ddlAccount", #class = "form-control" })
</div>
Is there any way I can achieve the same?
Note: model will contain only one account type at a time.
It works fine if I change the code like-
<div class="border col-md-2">
#Html.DropDownList("AccountType", new SelectList(new List<SelectListItem>
{ new SelectListItem { Text = "PWD-SUR", Value = "SBEN, SPPY, SPLF, SWOL" },
new SelectListItem { Text = "LOAN", Value = "LNPR"},
new SelectListItem { Text = "LN PYMT", Value = "LNIN"},
new SelectListItem { Text = "PREM", Value = "PREM"}
}, "Value", "Text", (Model.Account == "SBEN" || Model.Account == "SPPY" || Model.Account == "SPLF" || Model.Account == "SWOL") ? "SBEN, SPPY, SPLF, SWOL" : Model.Account), new { #id = "ddlAccount", #class = "form-control" })
</div>
According this article when you using SelectList, then you should specify SelectListItem value property which you want to set selected.
So you just need try like this:
<div class="border col-md-2">
#Html.DropDownListFor(model => model.Account, new SelectList(new List<SelectListItem>
{ new SelectListItem { Text = "PWD-SUR", Value = "SBEN, SPPY, SPLF, SWOL"},
new SelectListItem { Text = "LOAN", Value = "LNPR"},
new SelectListItem { Text = "LN PYMT", Value = "LNIN"},
new SelectListItem { Text = "PREM", Value = "PREM"}
}, "Value", "Text", (Model.Account == "SBEN" || Model.Account == "SPPY" || Model.Account == "SPLF" || Model.Account == "SWOL") ? "SBEN, SPPY, SPLF, SWOL" : Model.Account), new {#id="ddlAccount", #class = "form-control" })
</div>

Get the selected value using from dropdownlist using #Html.DropDownList

Here is the code below. the selected value senda to the controller.
#Html.DropDownList("pagesize", new List<SelectListItem>
{
new SelectListItem() {Text = "10", Value="10"},
new SelectListItem() {Text = "20", Value="20"},
new SelectListItem() {Text = "30", Value="30"},
new SelectListItem() {Text = "40", Value="40"}
}, new { onChange = string.Format("location.href = '{0}'", #Url.Action("Logs", "Logging")) })
Controller:-
public ActionResult Logs(int pagesize=10)
{
}
Remove the onChange attribute and use unobtrusive javascript. The function needs to add the selected value to the url as a route parameter.
var url = '#Url.Action("Logs", "Logging")';
$('#pagesize').change(function() {
location.href = url + '?pagesize=' + $(this).val();
}
Side note: You should be generating the SelectList in the controller, but in any case in can be simplified to
#Html.DropDownList("pagesize", new SelectList(new List<int>(){ 10, 20, 30, 40 }))

#Html.Dropdownlist(x => x.id, new int) not working

How i can make this work
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>MYep #Html.DropDownListFor(x => x.Id, new int {
new SelectListItem() {Text = "asdad", Value = "1"},
new SelectListItem() {Text = "dfgdgd", Value = "2"},
new SelectListItem() {Text = "werwrwt", Value = "3"}, "Choose")
<input type="submit" value="Ok" />
}
Or should I make a IEnumerable list before and give it to dropdownlistfor?
Matt's answer is fine, but it looks like you are using a ViewModel, so you should just put this static list into the view model and reference the list in your View.
ViewModel:
public sealed class MyViewModel
{
public int Id { get; set; }
public List<SelectListItem> IdList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "asdad", Value = "1" },
new SelectListItem { Text = "dfgdgd", Value = "2" },
new SelectListItem { Text = "werwrwt", Value = "3" }
};
}
}
}
View:
#Html.DropDownListFor(x => x.Id, Model.IdList)
You are declaring an object of type int and populating it with a List of SelectListItems, which will not work.
I think you want something like this... You may have to make some modifications if x.Id is an int and all the dropdown values are strings, but I'm not sure.
#Html.DropDownListFor(x => x.Id, new List<SelectListItem> {
new SelectListItem() {Text = "asdad", Value = "1"},
new SelectListItem() {Text = "dfgdgd", Value = "2"},
new SelectListItem() {Text = "werwrwt", Value = "3"}}, "Choose")

#Html.DropDownListFor How to add option?

#Html.DropDownListFor(model => model.ZipFile, new SelectList(ViewBag.ZipFiles))
The above code creates me a select list just fine. But I want to make the selection optional. Unfortunately there is no empty option and I'd like to add one in. How would I do this?
By using the proper DropDownListFor overload:
#Html.DropDownListFor(
model => model.ZipFile,
new SelectList(ViewBag.ZipFiles),
"-- please select a zip file --"
)
#Html.DropDownListFor(model => model.Country, new List<SelectListItem>
{
new SelectListItem { Text = "India", Value = "1"},
new SelectListItem { Text = "USA", Value = "2"},
new SelectListItem { Text = "Sreelanka", Value = "3"},
new SelectListItem {Text = "Africa",Value="4"},
new SelectListItem { Text = "China", Value = "5" },
new SelectListItem { Text = "Austraila", Value = "6" },
new SelectListItem { Text = "UK", Value = "7" }
}, "Select Country",
new {#Style = "Width:500px;height:40px;",
#class = "form-control input-lg"})
In the controller, when you set ViewBag.ZipFiles, add a SelectListItem to that collection.

Bind Html.DropDownList with static items

I have to bind an Html.DropDownList with just two items statically.
Text="Yes" Value="1"
Text="No" Value="0"
The important thing is that, I have to set the text and value fields.
How can I do this?
I used this is properly working
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
})
It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.
Example:
var list = new SelectList(new []
{
new { ID = "1", Name = "name1" },
new { ID = "2", Name = "name2" },
new { ID = "3", Name = "name3" },
},
"ID", "Name", 1);
ViewData["list"]=list;
return View();
you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.
in the View:
<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
Code below assumes you are using razor view engine if not you will need to convert it.
#{
var listItems = new List<ListItem>();
listItems.Add(new ListItem{Text="Yes", Value="1"});
listItems.Add(new ListItem{Text="No", Value="0"});
}
#Html.DropDownListFor(m=>m.SelectedValue, listItem);
You should consider creating the model in your code instead of the view. Also this would be a good candidate for an editor template.
if you want to be alittle explicity then try
#{
var domainsList = new SelectList(new []
{
new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
new SelectListItem { Text = ".Shopping", Value = ".shopping"},
new SelectListItem { Text = ".Org", Value = ".org"},
new SelectListItem { Text = ".Net", Value = ".net"},
new SelectListItem { Text = ".AE", Value = ".ae"},
new SelectListItem { Text = ".Info", Value = ".info"},
}, "Value", "Text");
}
#Html.DropDownList("TopLevelDomains", domainsList)
This solved it for me:
<td>
#{ var RlistItems = new List<SelectListItem>();
RlistItems.Add(new SelectListItem { Text = "Select Room Type", Value = "0" });
RlistItems.Add(new SelectListItem { Text = "Meeting Room", Value = "1" });
RlistItems.Add(new SelectListItem { Text = "Office", Value = "2" });
RlistItems.Add(new SelectListItem { Text = "Cafeteria", Value = "3" });
}
#Html.DropDownListFor(model=>model.FirstOrDefault().RoomType
,RlistItems,RlistItems[item.RoomType.Value].Selected=true )
</td>
<select asp-for="CountryName" asp-items=#(new List<SelectListItem> { new SelectListItem {Text="India",Value="1" } ,new SelectListItem {Text="Japan",Value="2" }} ) class="form-control">
<option>SELECT COUNTRY -- </option>

Resources