HTML Option values not being inputted into my controller - c#

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">
}

Related

Getting Select Option Value from Controller : ASP.NET MVC

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"];

Select tag helper to filter index

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.

Wrong bindind on select option ASP.NET MVC

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.

.Net Mvc RazorView & Entity Framework: Controller not found

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.

How to attach id to ng-model dynamically

<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles">
<option ng-repeat="role in clinicalRole" value="{{role.Description}}">{{role.Description}}</option>
</select>
Here I am getting data from server to list, I am only showing {{role.Description}} to user, but when I submit I need to attach role.id and role.Description to ng-Model for calling API.
You can do this with ng-options and select as: https://docs.angularjs.org/api/ng/directive/ngOptions
Don't use ng-repeat for that. Use ng-options instead.
Try this-
<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles"
ng-options="role.id as role.Description for role in clinicalRole">
</select>
If you want to select both at a time. Then you can use a trick. Add ng-change attribute in select and pass that selected role.id as it's model in a function.
HTML
<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles"
ng-options="role.id as role.Description for role in clinicalRole"
ng-change="setDescription(role)">
</select>
JS
$scope.lastSelectedDesc = {};
$scope.setDescription(role){
$scope.lastSelectedDesc = role;
}
Simply do this.
You can save complete object in ng-model instead of single property.
HTML :-
<div data-ng-app="myApp" data-ng-controller="Ctrl" style="margin-top:40px">
<div>
<select class="form-control" id="Region" data-ng-model="selectedValue" data-ng-options="value.Desc for value in values track by value.id">
<option value=''>Select</option>
</select>
</div>
<div>
Selected Option Label : {{selectedValue.label}}<hr/>
Selected Option Id : {{selectedValue.id}}<hr/>
Selected Option Desc : {{selectedValue.Desc}}<hr />
</div>
</div>
Javascript :-
<script type="text/javascript">
var IsApp = angular.module('myApp', []);
IsApp.controller('Ctrl', function ($scope, $http) {
$scope.values = [{
id: 1,
label: 'aLabel',
Desc: 'Desc-aLabel'
}, {
id: 2,
label: 'bLabel',
Desc: 'Desc-bLabel'
}];
});// End of controller
</script>
While submitting you can pass selectedValue.id and selectedValue.Desc.

Categories