This is the code in View Section:
<select name="country">
<option value="0">Select</option>
#foreach (var country in countries)
{
<option value="#country.CountryId"> #country.CountryName</option>
}
</select>
Code to get value from Controller:
public ActionResult IndexPost()
{
ViewBag.Countries = CountryRepository.GetCountries();
if (Request["btnSubmitCountry"] != null)
{
string country = Request["country"];
ViewBag.Msg = "You have selected " + country;
}
return View();
I wanted to Request to get value the name of the Country too, but right now it only gets the id. Can you please help me to get the id and name both using this only this method.
Because select returns the value of the value,But you can use the hidden tag to store the text value.
E.g:
<form onsubmit="var sel=document.getElementById('country');document.getElementById('country_text').value=sel.options[sel.selectedIndex].text;">
<select name="country" id="country">
<option value="0">Select</option>
#foreach (var country in countries)
{
<option value="#country.CountryId"> #country.CountryName</option>
}
</select>
<input type="hidden" name="country_text" id="country_text" />
</form>
get text:
string countryText = Request["country_text"];
Related
I want dropdown auto select value from DB while loading. For example i have values like this:
<option value="1">Mango</option>
<option value="2">Orange</option>
but I want when dropdown load orange selected because in previous form I already select orange.
<select class="form-control" data-plugin="select2" id="ddl_fruit" name="ddl_fruit" disabled="false" data-select2-id="2" tabindex="-1">
<option value="">Select fruit</option>
#if (ViewBag.fruitname!= null)
{
foreach (var item in ViewBag.fruitname)
{
<option value="#item.ID">#item.fruitname</option>
}
}
</select>
I am using ADO.NET and using not html.dropdown.
How do I solve the problem?
foreach (var item in ViewBag.fruitname)
{
if(#item.fruitname == "Orange")
<option value="#item.ID" selected = "selected">#item.fruitname</option>
else
<option value="#item.ID">#item.fruitname</option>
}
if you do not want to use if condition or html helpers then you use Jquery to select specific item.
Note: if you are using sections please put this code in it.
$(function(){ $('#ddl_fruit').val('2') // for orange })
Pass selected value in ViewBag.SelectedFruit from Controller to View.
In View:
foreach (var item in ViewBag.FruitName)
{
<option value="#item.Id" #(ViewBag.SelectedFruit == item.FruitName ? "selected" :"")>#item.FruitName</option>
}
I'm trying to use a select tag helper to filter a list of moves by difficulty and type. So far I have a working dropdown, but I have no idea how to redirect the selected value to the index method in my controller.
This is what I have
View
#model IEnumerable<Taijitan.Models.Domain.Move>
#{
ViewData["Title"] = "Moves";
}
<h2>#ViewData["Title"]</h2>
<div class="form-group">
//Returns filter1
<select asp-items="#ViewData["Difficulty"] as List<SelectListItem>" class="form-control">
<option value="">-- Select Difficulty --</option>
</select>
//Returns filter2
<select asp-items="#ViewData["Type"] as List<SelectListItem>" class="form-control">
<option value="">-- Select Type --</option>
</select>
</div>
The dropdown list is supposed to return the selected value to the index method, which takes a string as filter.
Controller
public IActionResult Index(string filter, string filter2)
{
IEnumerable<Move> Moves = null;
if (filter == null && filter2 == null){
Moves = _MoveRepository.GetAll();
}
else if (filter != null && filter2 == null)
{
Moves = _MoveRepository.GetByDifficulty(int.Parse(filter));
}
else if (filter == null && filter2 != null))
{
Moves = _MoveRepository.GetByType(filter);
}
else if (filter != null && filter2 != null))
{
Moves = _MoveRepository.GetByType(filter).Where(m => m.Difficulty == int.Parse(filter2);
}
ViewData["Type"] = GetTypesAsSelectList();
ViewData["Difficulty"] = GetDifficultiesAsSelectList();
return View(Moves);
}
Method which creates the displayed selectList (almost same for DifficultyList)
private List<SelectListItem> GetTypesAsSelectList()
{
List<SelectListItem> TypesList = new List<SelectListItem>();
foreach (Move move in _MoveRepository.GetAll().Distinct())
{
TypesList.Add(new SelectListItem { Text = Move.Type, Value = Move.Type });
}
return TypesList;
I'm stuck at figuring out how to pass the selected value of the dropdown lists as filter and filter2 to the index.
EDIT
I've added a form element and this button:
<a asp-controller="Move" asp-action="Index" asp-route-filter="" asp-route-filter2="" class="btn btn-default">Filter</a>
I can't figure out how to get the value of the first list in asp-route-filter, and the value of the second list in asp-route-filter2.
One core piece to a HTML form submit is the <form></form> element. Based on your question, I am assuming your form will be doing a GET instead of a POST. I assume this because the default action of a controller is a GET. Another is the SUBMIT button itself (unless you plan on submitting the form via javascript or other means).
You're also missing the asp-for="" which is a fancy way to populate the Name and Id of an element of a view. For your example, you would use filter and filter2 as the values. Though I would refactor those names in the future. The Name attribute allows the model binder to bind elements of the request to the controller's parameters.
With this in mind, your below form would look as follows (note the added FORM element, BUTTON element, and the addition of asp-for="").
#model IEnumerable<Taijitan.Models.Domain.Move>
#{
ViewData["Title"] = "Moves";
}
<h2>#ViewData["Title"]</h2>
<form method="GET">
<div class="form-group">
//Returns filter1
<select asp-items="#ViewData["Difficulty"] as List<SelectListItem>" class="form-control" asp-for="filter">
<option value="">-- Select Difficulty --</option>
</select>
//Returns filter2
<select asp-items="#ViewData["Type"] as List<SelectListItem>" class="form-control" asp-for="filter2">
<option value="">-- Select Type --</option>
</select>
<a asp-controller="Move" asp-action="Index" asp-route-filter="" asp-route-filter2="" class="btn btn-default">Filter</a>
</div>
</form>
You can use the #Html.Helpers for these elements as well. That's your choice. The results are the same.
When I post the form to the Controller, the binding on the VehiclePlate in asp-for gets the value of the select option (#vehicle.Category) but I want to get the text of the option (#vehicle.Plate) in the Controller. How can I do that?
This is my select:
#model Exam
...
<select asp-for="VehiclePlate" id="listVehicle" data-init-plugin="select2" style="width: 100%">
#foreach (var vehicle in ViewBag.Vehicles)
{
<option value="#vehicle.Category">#vehicle.Plate</option>
}
</select>
And this is my Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Exam exam)
{
...
}
The select tag has an asp-items attribute which you can set to a SelectList, e.g
<select asp-for="VehiclePlate" asp-items='new SelectList(ViewBag.Vehicles, "Plate", "Plate")'>
</select>
The "Plate", "Plate" part means, that the select uses Plate as value and as text for the dropdown.
I am using Razorview and Entity Framework and I am trying to achieve the following: I have a dropdown(id=ColumnName) that has a list of column names and a textbox(id=SearchValue) for value to be searched from a table. On click of a button, I am trying to retrieve from the database, the record where the column name is 'ColumnName' selected and value='SearchValue'. I am getting a 404 Resource Not found error on click of the button. I am not sure where I am going wrong. My code is as follows:
HTML:
<select id='mySelector' name="ColumnName">
<option value="">Please Select</option>
<option value='Country'>Country</option>
<option value='Title'>Title</option>
<option value='State'>State</option>
</select>
<input type="text" id="cs" name="SearchValue">
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
<table id='myTable'>
// values
</table>
CountryController:
public ActionResult FilterByColumn(String ColumnName, String SearchValue)
{
if (!String.IsNullOrEmpty(SearchValue))
{
List<Country> result = new List<Country>();
result = db.Countries.ToList();
result = db.Countries.Where(ColumnName + ".Contains" + "(\"" + SearchValue.ToLower() + "\")").ToList();
return View(result);
}
return RedirectToAction("Index");
}
Note: I have other methods like create,edit in this controller.
Also the URL rendered which throws the 404 error is :
/CountryController/FilterByColumn?SearchValue=sample&ColumnName=Title
Your code as flollows
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
Never give CountryController, just Give Country and try. Edit your code as follows and try
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "Country")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
and give the parameters in same order in both razor and controller
your button code as follows
input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
but in the controller you have written as follows
public ActionResult FilterByColumn(String ColumnName, String SearchValue)
but the order of parameters are different. So change your controller as follows.
public ActionResult FilterByColumn(String SearchValue,String ColumnName)
Hope this will work out.
In the following controller method
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
PortalData PD = new PortalData();
if (file != null && file.ContentLength > 0)
try
{
string[] newFileNamePieces = { selectedOrgName, selectedCatName, Path.GetFileName(file.FileName) };
string newFileName = string.Join("-", newFileNamePieces); // Creates new file name of the form [organization]-[category]-[file name with extension]
file.SaveAs(Path.Combine(Server.MapPath("~/Assets"),newFileName)); // Saves file with new file name in assets folder
string fileId = Guid.NewGuid().ToString().Replace("-", string.Empty); // randomly generated file id (a GUID without any hyphens)
// e.g. 752355644d434751866653da303a40b1
ViewBag.Message = string.Format("File {0} ({1}KB) uploaded and saved successfully! File ID: {2}. File should be found at {3}", newFileName, (file.ContentLength / 1024).ToString(), fileId, Path.Combine(Server.MapPath("~/assets"),newFileName));
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
ViewBag.orgcatJSON = PD.mapOrgs2Cats();
return View();
}
where selectedOrgName and selectedCatName are supposed to come from the <Select> elements
<select class="selectpicker" name="selectedOrgName" id="orglist">
<!-- houses the Option elements corresponding to organizations -->
<option value="companyA">companyA</option>
<option value="companyB">companyB</option
</select>
and
<select class="selectpicker" name="selectedCatName" id="catlist">
!-- houses the options elements corresponding to the categories for the organization selected in #orglist -->
<option value="somecategory">somecategory</option>
</select>
I'm noticing that selectedOrgName and selectedCatName are empty when my method is invoked. Based upon the code I've posted, is there any glaring reason why this is?
The issue seems to be that the select elements were defined outside the form element (which posts them as null in the Controller):
#using (Html.BeginForm("Index", "Home", FormMethod.Post)){
<input type="submit" value="Submit">
}
<select class="selectpicker" name="selectedOrgName" id="orglist">
<!-- houses the Option elements corresponding to organizations -->
<option value="companyA">companyA</option>
<option value="companyB">
companyB
</option>
</select>
They need to be inside the form to be assigned by MVC as a parameter in the Controller (correct version):
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<select class="selectpicker" name="selectedOrgName" id="orglist">
<!-- houses the Option elements corresponding to organizations -->
<option value="companyA">companyA</option>
<option value="companyB">
companyB
</option>
</select>
<input type="submit" value="Submit">
}