How to convert Actionlink group to Dropdown List - c#

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)
{
...
}

Related

Is it possible to use link inside DropDownList html helper?

I have a model class named categories that retrieves data from database :
public class HomeController : Controller
{
private StoreContext db;
public HomeController()
{
db = new StoreContext();
}
public ActionResult Categories()
{
return View(db.Categories.ToList());
}
}
I want to use DropDownList helper method to display them in the view and I want all the categories inside it to be clickable, say, when you click them it has to adress you to the specified url belongs to the clicked category. Is there a way to make this happen with DropDownList helper? if yes then how?
You can do this but you have to use Jquery . If you ask how?
For example:
My sample entity
public class Category
{
public int Id { get; set; }
public string Url{ get; set; }
public string Name { get; set; }
}
My action:
public IActionResult Categories()
{
var list = new List<Category>();
for (int i = 0; i < 10; i++)
{
list.Add(new Category(){Id = i, Url = "https://stackoverflow.com", Name = "stackoverflow" });
}
var selectList = list.Select(x => new SelectListItem() {Value = Url, Text = x.Name})
.ToList();
return View(selectList);
}
in my View:
#Html.DropDownList("url",Model, "Choose a URL", new { id = "url_list" })
and then using jquery you could subscribe for the change event of this dropdownlist and navigate to the corresponding url:
$(function() {
$('#url_list').change(function() {
var url = $(this).val();
if (url != null && url != '') {
window.location.href = url;
}
});
});

ASP.NET MVC one of the forms dont get validation messages

My problem is this: I have created a view in which I want to be able to remove and add new identity roles. For that I created two forms that call two different actions. I have created a big model which consists of smaller models which are bound by the forms to the actions. Everything works as intended, models get bound properly, data is there and proper actions are executed as they should.
Don't get me wrong, I understand those are separate forms and I know they will never show validation messages both at the same time because only one form can be posted at a time. The problem is that when I click submit on the CreateNewRole form, the validation message is there, but when I click submit on the RemoveRoles action, I don't get any validation messages and no validation classes are applied to the html elements, there is the usual "field-validation-valid" and no "field-validation-error" class in it while its perfectly present in CreateNewRole.
Why does validation work on the first form but not on the second form? I cant find any difference in how i made those two forms, am i not noticing something?
When I debug modelstate of the RemoveRoles action, the error is there, but somehow the view isn't getting informed of it.
View
#model Models.ViewModels.RolePanelViewModel
#using Extensions
<h2>Role Panel</h2>
<article>
<div class="admin-panel-flex-container">
<div class="form-container">
#using (Html.BeginForm("CreateNewRole", "Administrator"))
{
<div class="form-group">
#Html.LabelFor(l => l.NewRoleRolePanelViewModel.NewIdentityRole.Name)
#Html.TextBoxFor(t => t.NewRoleRolePanelViewModel.NewIdentityRole.Name)
#Html.ValidationMessageFor(t => t.NewRoleRolePanelViewModel.NewIdentityRole.Name)
<button type="submit">Dodaj role</button>
</div>
}
</div>
<div class="form-container">
#using (Html.BeginForm("RemoveRoles", "Administrator"))
{
<div class="form-group">
#Html.LabelFor(l => l.ListRolePanelViewModel.SelectedIdentityRoles)
#Html.ListBoxFor(l => l.ListRolePanelViewModel.SelectedIdentityRoles, #Model.ListRolePanelViewModel.IdentityRolesSelectListItems)
#Html.ValidationMessageFor(t => t.ListRolePanelViewModel.SelectedIdentityRoles)
<button type="submit">Skasuj wybrane</button>
</div>
}
</div>
</div>
</article>
Models
public class RolePanelViewModel
{
public ListRolePanelViewModel ListRolePanelViewModel { get; set; }
public NewRoleRolePanelViewModel NewRoleRolePanelViewModel { get; set; }
}
public class ListRolePanelViewModel
{
public List<IdentityRoleDTO> IdentityRoles { get; set; }
public List<SelectListItem> IdentityRolesSelectListItems { get; set; }
[Required(ErrorMessage = "Należy wybrać przynajmniej jedną pozycję z listy")]
public List<string> SelectedIdentityRoles { get; set; }
}
public class NewRoleRolePanelViewModel
{
public IdentityRoleDTO NewIdentityRole { get; set; }
}
public class IdentityRoleDTO
{
public string Id { get; set; }
[Required(ErrorMessage = "Nowa rola musi mieć nazwę")]
[MinLength(5)]
public string Name { get; set; }
public List<IdentityUserRole> Users { get; set; }
}
Actions
public ActionResult OpenRolePanel()
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = new ListRolePanelViewModel
{
IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem {Value = a.Id.ToString(), Selected = false, Text = a.Name})
},
NewRoleRolePanelViewModel = new NewRoleRolePanelViewModel()
};
return View("RolePanel", viewModel);
}
[HttpPost]
public async Task<ActionResult> CreateNewRole(NewRoleRolePanelViewModel newRoleRolePanelViewModel)
{
if(!ModelState.IsValid)
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = new ListRolePanelViewModel
{
IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem { Value = a.Id.ToString(), Selected = false, Text = a.Name })
},
NewRoleRolePanelViewModel = newRoleRolePanelViewModel
};
return View("RolePanel", viewModel);
}
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
await roleManager.CreateAsync(new IdentityRole(newRoleRolePanelViewModel.NewIdentityRole.Name));
return View("RolePanel");
}
[HttpPost]
public ActionResult RemoveRoles(ListRolePanelViewModel listRolePanelViewModel)
{
if (!ModelState.IsValid)
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = listRolePanelViewModel,
NewRoleRolePanelViewModel = new NewRoleRolePanelViewModel()
};
viewModel.ListRolePanelViewModel.IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem {Value = a.Id.ToString(), Selected = false, Text = a.Name});
return View("RolePanel", viewModel);
}
return View("RolePanel");
}
Custom method that may be needed if you want to run the code
private List<SelectListItem> GetSelectListItems<T>(List<T> dbSetResult, Func<T,SelectListItem> Func)
{
var result = new List<SelectListItem>();
foreach (var item in dbSetResult)
{
result.Add(Func(item));
}
return result;
}

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();
});

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

Implementing a Slider in ASP.NET MVC?

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")
) %>

Categories

Resources