Implementing a Slider in ASP.NET MVC? - c#

I am working in Slider Concept in ASP.NET MVC 2.
slider code snippet
<script type="text/javascript">
$(function () {
var abc = $('select#speed').selectToUISlider().next();
fixToolTipColor();
});
function fixToolTipColor() {
$('.ui-tooltip-pointer-down-inner').each(function () {
var bWidth = $('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = $(this).parents('.ui-slider-tooltip').css('backgroundColor')
$(this).css('border-top', bWidth + ' solid ' + bColor);
});
}
</script>
<form action="#">
<fieldset>
<select name="speed" id="speed">
<option value="Poor">Poor</option>
<option value="Good">Good</option>
<option value="Med">Med</option>
<option value="VeryGood">VeryGood</option>
<option value="Excellent">Excellent</option>
</select>
</fieldset>
</form>
I don't understand how to load the slider with dynamic values (based on calculations or numbers from the database)
How do I do this?
Right now I populate a dropdownlist using the following SQL. How can this be used to populate the slider?
private void PopulateGradeScale(string tenantID)
{
List<scale> AttributesList = new List<scale>();
if (!string.IsNullOrEmpty(tenantID))
{
Context.SetPrivilegeContext(PrivilegeConstant.ViewEmployee);
Dictionary<string, scale> Attributes = Proxy.GetGrade(UserIdentity.TenantID);
if (Attributes != null && Attributes.Count > 0)
{
AttributesList = Attributes.Values.ToList();
}
}
if (!string.IsNullOrEmpty(tenantID))
ViewData["Grade"] = new SelectList((IEnumerable)AttributesList, "Identifier", "Name");
else
ViewData["Grade"] = new SelectList((IEnumerable)AttributesList, "Identifier", "Name");
}

As always you start with defining a view model which will represent your data for this given view:
public class SliderViewModel
{
public string SelectedSpeed { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public string Value { get; set; }
public string Text { get; set; }
}
Next you have a controller action which will use a repository to query the database and fill the view model which will be passed to a strongly typed view:
public ActionResult Index()
{
var model = new SliderViewModel
{
Items = new[]
{
new Item { Value = "Poor", Text = "Poor" },
new Item { Value = "Good", Text = "Good" },
new Item { Value = "Med", Text = "Med" },
new Item { Value = "VeryGood", Text = "VeryGood" },
new Item { Value = "Excellent", Text = "Excellent" }
}
};
return View(model);
}
and finally you use an HTML helper in the view to generate the dropdown":
<%= Html.DropDownListFor(
x => x.SelectedSpeed,
new SelectList(Model.Items, "Value", "Text")
) %>

Related

How to filter select list based on selection of another select list using Blazor?

I am having a problem understanding the cleanest way to filter a dropdown dependent on the selection of another dropdown. The trick here is taking into account things such as: What if the user initially selects something in the States dropdown and then resets the States dropdown by selecting Choose..., I would want the Companies dropdown to reset back to Choose... as well. I am having issues with this because Blazor doesn't appear to allow me to two-way bind to a property such as SelectedStateId and additionally call a function change. I would have zero issues if it did because this is how I do it in Angular. It looks like I am stuck with either using two way binding or calling a function onchange, but can't do both. Am I missing something here?
A few things/questions:
Pretend I am loading the initial lists in from a service, but for
now I am hardcoding. (I believe I accomplished this)
If user resets the State dropdown at any point I want to reset the Companies dropdown as well.
Do I really need to create two separate lists for Companies to accomplish this. One to keep the state of the initial list of companies and one to manage the filtered list that the dropdown will be set to.
If I remove the onchange event and replace it with bind-value I will lose the ability to call a function to filter. Wont I?
Here is my code:
#page "/"
<PageTitle>Index</PageTitle>
<div class="mb-3">
<label for="state" class="form-label">State</label>
<select id="state" class="form-select" #onchange="stateChanged">
<option value="0" selected>Choose...</option>
#foreach (var state in StatesDb)
{
<option value="#state.Id">#state.Name</option>
}
</select>
</div>
<div class="mb-3">
<label for="company" class="form-label">Company</label>
<select id="company" class="form-select" #onchange="companyChanged">
<option value="0" selected>Choose...</option>
#foreach (var company in CompaniesDb)
{
<option value="#company.Id">#company.Name</option>
}
</select>
</div>
#code {
List<State> StatesDb { get; set; }
List<Company> CompaniesDb { get; set; }
List<State> CompaniesFiltered { get; set; }
int? SelectedStateId { get; set; }
int? SelectedCompanyId { get; set; }
protected override void OnInitialized()
{
StatesDb = new List<State>() {
new State(){ Id = 1, Name = "Delaware", Abbreviation = "DE"},
new State(){ Id = 2, Name = "Pennslyvania", Abbreviation = "PA"},
new State(){ Id = 3, Name = "New Jersey", Abbreviation = "NJ"},
};
CompaniesDb = new List<Utility>() {
new Company(){ Id = 1, Name = "Company 1", StateIds = { 1 } },
new Company(){ Id = 2, Name = "Company 2", StateIds = { 2 } },
new Company(){ Id = 3, Name = "Company 3", StateIds = { 1,3 }
}
};
CompaniesFiltered = CompaniesDb;
}
void stateChanged(ChangeEventArgs e) {
int value = int.Parse(e.Value.ToString());
if (value != 0) {
SelectedStateId = value;
}
filterCompanies();
}
void filterCompanies() {
CompaniesFiltered = CompaniesDb.Where(x => (SelectedStateId == null || x.StateIds.Contains((int)SelectedStateId))).ToList();
}
}
You should act as follows to be able to have both data binding and UI change:
<CustomInputSelect ValueExpression="#(()=>state.Id)"
Value="#state.Id"
ValueChanged="#((int value) => stateChanged(value ))" id="state">
<ValidationMessage For="()=>state.Id"></ValidationMessage>
#foreach (var item in StatesDb)
{
<option value="#state.Id">#state.Name</option>
}
</CustomInputSelect>
You can see the CustomInputSelect implementation in this post.
Finally, the stateChanged method can implement as follows:
void stateChanged(int value) {
if (value != 0) {
SelectedStateId = value;
}
filterCompanies();
}
Here's a one page demo that shows how you can achieve what I think you are trying to do. And hopefully answers your questions.
I wasn't sure of the difference between a State and a Utility, so I've treated them as one.
I've created Company and State based on your code.
All the lists/arrays are abstracted as IEnumerable<>.
I've refactored some of the code to keep the demo as clean as possible.
#page "/"
<PageTitle>Index</PageTitle>
<div class="mb-3">
<label for="state" class="form-label">State</label>
<select id="state" class="form-select" #bind=SelectedStateId>
#this.ShowChoose(SelectedStateId)
#foreach (var state in StatesDb)
{
<option value="#state.Id">#state.Name</option>
}
</select>
</div>
<div class="mb-3">
<label for="company" class="form-label">Company</label>
<select id="company" class="form-select" disabled="#this.IsCompanyDisabled" #bind=SelectedCompanyId>
#this.ShowChoose(SelectedCompanyId)
#foreach (var company in CompaniesFiltered)
{
<option value="#company.Id">#company.Name</option>
}
</select>
</div>
#code {
private IEnumerable<State> StatesDb { get; set; } = new List<State>() {
new State(){ Id = 1, Name = "Delaware", Abbreviation = "DE"},
new State(){ Id = 2, Name = "Pennslyvania", Abbreviation = "PA"},
new State(){ Id = 3, Name = "New Jersey", Abbreviation = "NJ"},
};
private IEnumerable<Company> CompaniesDb { get; set; } = new List<Company>() {
new Company(){ Id = 1, Name = "Company 1", StateIds = new List<int> { 1 } },
new Company(){ Id = 2, Name = "Company 2", StateIds = new List<int> { 2 } },
new Company(){ Id = 3, Name = "Company 3", StateIds = new List<int> { 1,3 }
}
};
private IEnumerable<Company> CompaniesFiltered
=> CompaniesDb.Where(x => (SelectedStateId == null || x.StateIds.Contains((int)SelectedStateId))).ToList();
private bool IsCompanyDisabled => SelectedStateId is null || SelectedStateId == 0;
int? _selectedStateId = 0;
int? SelectedStateId
{
get => _selectedStateId;
set
{
if (value != _selectedStateId)
{
_selectedStateId = value;
SelectedCompanyId = 0;
}
}
}
int? SelectedCompanyId { get; set; }
private RenderFragment ShowChoose(int? value) => (__builder) =>
{
if (value is null || value == 0)
{
<option value="0" disabled selected>Choose...</option>
}
};
public class State
{
public int Id { get; set; }
public string Name { get; set; } = "No Name Provided";
public string Abbreviation { get; set; } = "No Abbreviation Provided";
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; } = "No Name Provided";
public IEnumerable<int> StateIds { get; set; } = Enumerable.Empty<int>();
}
}

How to convert Actionlink group to Dropdown List

the SiteLanguage cs file:
public class SiteLanguages
{
public static List<Languages> AvailableLanguages = new List<Languages>
{
new Languages{ LangFullName = "English", LangCultureName = "en"},
new Languages{ LangFullName = "Español", LangCultureName = "es"},
new Languages{ LangFullName = "বাংলা", LangCultureName = "bn"}
};
public class Languages
{
public string LangFullName { get; set; }
public string LangCultureName { get; set; }
}
}
cshtml file:
#{
foreach (var i in MvcMultilingual.SiteLanguages.AvailableLanguages)
{
#Html.ActionLink(i.LangFullName, "ChangeLanguage", "Home", new{lang = i.LangCultureName}, null) <text> </text>
}
}
I want to convert this action list group to dropdown list. How to change this code? I mean I just want to change cshtml side. Html.ActionLink to Html.DropdownList etc.
Try the following:
#using Languages = MvcMultilingual.SiteLanguages
#Html.DropDownListFor(m => Languages.AvailableLanguages.GetEnumerator().Current,
Languages.AvailableLanguages.Select(d =>
{
return new SelectListItem() {
Text = d.LangFullName,
Value = Url.Action("SetLanguage", "Home", new { lang = d.LangCultureName })
};
}),
"-Select Language-",
new { id = "urlddl" })
See the javascript function for processing the change event in this post: is it possible do have Html.ActionLink inside a DropDownList Without java script?
Processing the selected value on the controller side:
public ActionResult SetLanguage(string lang)
{
...
}

asp.net mvc Html.DropDownListFor: how to handle selected id

I have a problem with using #Html.DropDownListFor element.
What i have:
Model 'DatabaseModel':
public class DirectionEntity
{
public string Id { get; set; }
public string DirectionName { get; set; }
}
public class ViewModel
{
public int SelectedDirectionID { get; set; }
public List<DirectionEntity> DirectionList { get; set; }
}
Model 'DataFactory':
public class DataFactory
{
public static ViewModel Refresh()
{
using (var db = new MyDatabase())
{
return new ViewModel()
{
DirectionList = db.Directions.Select(_ => new { _.Id, _.DirectionName })
.ToList()
.Select(_ => new DirectionEntity() { Id = _.Id.ToString(), DirectionName = _.DirectionName })
.ToList(),
};
}
}
}
Controller:
public System.Web.Mvc.ActionResult AddNewDocument()
{
var db = DataFactory.Refresh();
return View(db);
}
[HttpPost]
public System.Web.Mvc.ActionResult AddNewEntry(ViewModel m)
{
m = DataFactory.Save(m);
ModelState.Clear();
return View(<some view>);
}
View:
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedDirectionID, new SelectList(Model.DirectionList.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DirectionName }), "Value", "Text"), new { #class = "Duration", required = "required" })
<button type="submit" class="btn btn-default SaveAll">Save</button>
}
The question:
How to handle 'SelectedDirectionID' value, after user selected some position on dropdownlist, but not yet sent the request to the server using a POST-method.
See what the id of your dropdown is and then you can subscribe to the change event on the client side. You can do this using jQuery.
$("#idOfYourDropDown").change(function () {
// Do whatever you need to do here
// Here are some ways you can get certain things
var end = this.value;
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
Also you should see my answer here on why you should not return a view from a POST action the way you are.
In this case you have to use Jquery. As per your view id for your drop down is 'SelectedDirectionID';
Your Js:
$(document).ready(function () {
var selectedValue = $('#SelectedDirectionID').val();
var selectedText = $("#SelectedDirectionID option:selected").text();
});
Or Inside drop down change event.
$('#SelectedDirectionID').change(function () {
var selectedValue = $(this).val();
var selectedText = $(this).find("option:selected").text();
});

ASP.NET MVC 3 - Javascript breaks SelectedValue from DropDownList

I have a ViewModel and a DropDownList with some values on my page:
public class MyViewModel
{
public string SelectedItemDrop1 { get; set; }
public string SelectedItemDrop2 { get; set; }
public string SelectedItemDrop3 { get; set; }
public List<OptionViewModel> Options { get; set; }
}
public class OptionViewModel
{
public string Number { get; set; }
public string Option { get; set; }
}
And, into my View:
#using (Html.BeginForm("Save", "Controller", FormMethod.Post))
{
<ul id="cursos">
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop1,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop1))
Choose 1
</li>
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop2,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop2))
Choose 2
</li>
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop3,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop3))
Choose 3
</li>
</ul>
}
When I use Javascript to change options from these select elements, my return is null. What's the problem? Thank you so much!!!
EDIT:
My javascript code:
$("#cursos li select").each(function (i, item) {
$(this).change(function () {
updateCursos($(this), 7);
});
$(this).blur(function () {
if ($(this).val() != -1) {
$(this).attr('disabled', 'disabled');
}
});
});
function updateCursos(select, avaiableCourses) {
var selecteds = '';
$("#cursos li select").each(function (i, item) {
var selected = $(item).val();
if (selected != -1)
selecteds += selected + ',';
});
var arr = selecteds.split(',');
$("#cursos li select").each(function (i, item) {
if ($(item).val() != select.val()) {
var oldValue = $(item).val();
if ($(item).val() == -1) {
var options = "<option value='-1'></option>";
for (i = 1; i <= avaiableCourses; ++i) {
if (select.val() != i && !contains(i, selecteds)) {
options += "<option value='" + i + "'>" + i + "ª option</option>";
}
}
options += "<option value='0'>Don't want it</option>";
$(item).children("option").remove();
$(item).html(options);
$(item).val(oldValue);
}
}
});
}
This way I'm sure that works, not even being javascript.
If the values ​​are not being filled are coming from the database, with fixed values ​​example: active, inactive, do the following
Create an enumerated type with these values
After the controller transforms this type enumerated in list using an internal class, turn it into a enumerable and go to the dropdownlist
example of usage:
# Html.DropDownListFor (model => model.chamados.UrgenciaId, new SelectList (ViewBag.urgencia, "Id", "Name"))

How to update a textarea in the current view on Submit in ASP.net MVC 3?

I have a page that has two drop down lists and based upon the selection of these two lists I would like to populate a textarea with some data on submit button press.
The behavior that I am seeing while debugging is that the page is rendered, I make my selections and press submit. The DataAccess returns the correct results and the View returns, but with an exception "There is no ViewData item of type 'IEnumerable' that has the key 'People'.
I can see that I could re-setup the drop down lists, but it feels like I'm approaching this incorrectly. Is there another approach for doing this sort of action in MVC 3?
public ActionResult Test()
{
//People for dropdownlist 1
var db = peopleRepository.People;
var query = db.Select(c => new {c.Id, c.Name});
ViewBag.People = new SelectList(query.AsEnumerable(), "Id", "Name");
//Elements for dropdownlist 2
var list = new Dictionary<string, string> {{"1", "Name"}, {"2", "Address"}, {"3", "Zip"}};
ViewBag.Elements = new SelectList(list, "Key", "Value");
return View();
}
// This part is what I'm confused about.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test(string people, string elements)
{
if (ModelState.IsValid)
{
// Output from persistent storage query
var da = new DatabaseAccess(people, elements);
ViewBag.Results = da.Execute();
}
return View();
}
View:
#using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
#Html.DropDownList("People", (SelectList)ViewBag.People, "--Select One--")
#Html.DropDownList("Elements", (SelectList)ViewBag.Elements, "--Select One--")
#Html.TextArea("Results", (string)ViewBag.Results, 10, 120, "")
}
Here is how I would quickly construct it :
Model :
public class People
{
public int Id { get; set; }
public string Name { get; set; }
}
ViewModel (everything needed by the view):
public class TestViewModel
{
public int SelectedPeopleId { get; set; }
public string SelectedElementId { get; set; }
public SelectList People { get; set; }
public SelectList Elements { get; set; }
public String Results { get; set; }
}
Controller (used Index as the default Action, create an init function for the view model that can be adapted)to anything more appropriate :
public class HomeController : Controller
{
private static TestViewModel InitTestVM()
{
//People for dropdownlist 1
var db = new List<People>();//peopleRepository.People;
db.Add(new People { Id = 1, Name = "Name 1" });
db.Add(new People { Id = 2, Name = "Name 2" });
var query = db.Select(c => new { c.Id, c.Name });
//Elements for dropdownlist 2
var list = new Dictionary<string, string> { { "1", "Name" }, { "2", "Address" }, { "3", "Zip" } };
TestViewModel testVM = new TestViewModel
{
People = new SelectList(query.AsEnumerable(), "Id", "Name"),
Elements = new SelectList(list, "Key", "Value")
};
return testVM;
}
public ActionResult Index()
{
return View(InitTestVM());
}
// This part is what I'm confused about.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(TestViewModel testVM)
{
var vm = InitTestVM();
if (ModelState.IsValid && testVM != null)
{
ModelState.Clear();
// Output from persistent storage query
//var da = new DatabaseAccess(people, elements);
vm.Results = "sfdfsdfsdfsdfsdfsdfsdfsdf";//da.Execute();
vm.SelectedElementId = testVM.SelectedElementId;
vm.SelectedPeopleId = testVM.SelectedPeopleId;
return View(vm);
}
return View(vm);
}
}
And finally the View :
#model ViewModels.TestViewModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedPeopleId, Model.People, "--Select One--")
#Html.DropDownListFor(m => m.SelectedElementId, Model.Elements, "--Select One--")
#Html.TextAreaFor(m => m.Results, 10, 120, "")
<input type="submit" value="Test" />
}

Categories

Resources