Populating a Html.Listbox with all ASP.NET users - c#

I'm trying to create a page where a listbox will contain all my ASP.NET users.
However I'm having a lot of problems attempting to make the Html.Listbox accept the list of users.
I have tried doing this:
<%: Html.ListBox("Membershipusers", Membership.GetAllUsers())%>
and a zillion other approaches that is similar to this. I also have a method on my controller that looks like this:
public ActionResult getAllMembershipUsers()
{
MembershipUserCollection membershipusers = new MembershipUserCollection();
membershipusers = Membership.GetAllUsers();
return View(membershipusers);
}
It seems like it is able to create the list of users, but I still don't know how to show that list in my listbox.
Hope somebody can help me out here.

How about using a view model? Have you tried this approach?
public class UsersViewModel
{
public IEnumerable<string> SelectedUsers { get; set; }
public IEnumerable<SelectListItem> AvailableUsers { get; set; }
}
and then a controller which will populate this view model:
public ActionResult Index()
{
var users = Membership.GetAllUsers().Cast<MembershipUser>();
var model = new UsersViewModel
{
AvailableUsers = users.Select(u => new SelectListItem
{
Value = u.UserName,
Text = u.UserName
})
};
return View(model);
}
and finally in your strongly typed view to the view model
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<UsersViewModel>" %>
...
<%= Html.ListBoxFor(x => x.SelectedUsers, Model.AvailableUsers) %>

Related

MVC actionlink passing list of objects

I've got a view that looks like this:
With this view I'm filtering records which are in a database. Each "filter" is a SearchViewModel which has a class definition like this:
public class SearchViewModel
{
//Property has a property called "SqlColumnName"
public Property Property { get; set; }
public Enums.SearchOperator Operator { get; set; }
public string Value { get; set; }
}
I'm now trying to find a solution how to build a actionlink to this site and passing in a List<SearchViewModel>().
So I'm trying to accomplish something like this:
http://url/Index?property=Typ&Operator=2&Value=4&property=ServerName&Operator=1&Value=server
I've tried to solve my problem with this http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ but this guy is calling the Action with a POST and i need to call it with a GET request.
So how to pass a list of objects to a mvc controller action with an actionlink?
EDIT
I think i need to say, that POST request is not an option because i need that link in an onClick event of a div element.
You could construct a link with the following parameters that should work:
http://url/Index?%5B0%5D0.property=Typ&%5B0%5D0.Operator=2&%5B0%5D0.Value=4&%5B1%5D0.property=ServerName&%5B1%5D0.Operator=1&%5B1%5D0.Value=server
Also notice that there are restrictions in the length of query string parameters. Those restrictions vary between the browsers. So it's probably a better approach to simply generate a link with an id that would allow you to retrieve the corresponding collection on the server (from your datastore):
http://url/Index?id=123
ActionLink helper method renders an anchor tag. It is ok to pass few query string items via a link. Remember Query string has a limit about how much data you can pass and it varies from browser to browser.
What you should be doing is a form posting. You can do a form posting on a click event on a div with the help of a little javascript.
Let's create a new view model for our search page
public class SearchVm
{
public List<SelectListItem> Operators { set; get; }
public List<SearchViewModel> Filters { set; get; }
}
public class SearchViewModel
{
//Property has a property called "SqlColumnName"
public Property Property { get; set; }
public SearchOperator Operator { get; set; }
public string Value { get; set; }
}
So in your GET action, You will send a list of SearchViewModel to the view.
public ActionResult Index()
{
var search = new SearchVm
{
Filters = new List<SearchViewModel>
{
new SearchViewModel {Property = new Property {SqlColumn = "Name"}},
new SearchViewModel {Property = new Property {SqlColumn = "Age"}},
new SearchViewModel {Property = new Property {SqlColumn = "Location"}}
}
};
//Convert the Enums to a List of SelectListItem
search.Operators= Enum.GetValues(typeof(SearchOperator)).Cast<SearchOperator>()
.Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList();
return View(search);
}
And in your view, which is strongly typed to your SearchVm view model, We will manipulate the form field names so that the model binding will work when the form is submitted.
#model SearchVm
#using (Html.BeginForm())
{
var i = 0;
foreach (var criteria in Model.Filters)
{
<label>#criteria.Property.SqlColumn</label>
#Html.HiddenFor(f => f.Filters[i].Property.SqlColumn)
#Html.DropDownList("Filters[" + i+ "].Operator",Model.Operators)
#Html.TextBoxFor(f=>f.Filters[i].Value)
i++;
}
<div id="someDiv">Search button using Div</div>
<input type="submit" value="Search" />
}
And your HttpPost action method to handle the form submit.
[HttpPost]
public ActionResult Index(SearchVm model)
{
foreach(var f in model.Filters)
{
//check f.Property.SqlColumn, f.Value & f.Operator
}
// to do :Return something useful
}
If you want the form to be submitted on the click event on the div, Listen to the click event on the specific div and call the submit method on the form the div resides in.
<script>
$(function () {
$("#someDiv").click(function(e) {
$(this).closest("form").submit();
});
});
</script>

I Can't get a DropDownList to populate from table. EF and MVC4

I believe this will create a list in my HomeController. But not sure what calls it or where it goes in the Controller beside maybe the first Add ActionResult (GET method).
public static IEnumerable<SelectListItem> items()
{
using (oesacEntities_compact db = new oesacEntities_compact())
{
var query = from s in db.tblSponsors select new { s.SponsorID, s.BizName };
return query.AsEnumerable()
.Select(x => new SelectListItem
{
Value=x.SponsorID.ToString(),
Text = x.BizName
}).ToList();
}
}
I can't seem to send it to the Add view or to reference it from the Add view:
<div class="editor=field">
#Html.DropDownListFor(model => model.SponsorID,IEnumerable<SelectListItem> SelectList);
</div>
It seems so simple in other coding languages. I want to populate a pulldown with about 200 sponsor ID's for value, BizNames for text. For now at least. God help me after that when I want to show an Edit view with the value selected.
thankyou stackoverflow
You need to pass the SelectList to your view. Ideally your view model should include a property for the SelectList but you can (yuk) use ViewBag, for example
View Model
public class MyViewModel
{
public int SponsorID { get; set; }
// other properties
public SelectList SponsorList { get; set; }
}
Controller
public ActionResult SomeThing()
{
MyViewModel model = new MyViewModel();
// assign the select list
var sponsors = from s in db.tblSponsors;
model.SponsorList = new SelecList(sponsors, "SponsorID", "BizName");
return View(model);
}
View
#Html.DropDownListFor(model => model.SponsorID, Model.SponsorList);
or if you assigned the select list to ViewBag
#Html.DropDownListFor(model => model.SponsorID, (SelectList)ViewBag.SponsorList);

Do you always have to set ViewBag variables in order to access data from the controller

I have a controller like this:
public ActionResult Index()
{
ViewBag.Title = "Index";
ViewBag.LoggedIn = TheUser.CheckStatus();
return View();
}
Thing is, I have to set LoggedIn to the output of my other function TheUser.CheckStatus() so that I can reference it with razor... Is there a way in Razor to access a function straight off? for example...
#TheUser.CheckStatus
instead of
#ViewBag.LoggedIn
The recommended way in MVC for passing information to a view is to create a model specific to that view (aka view model) e.g.
public class IndexViewModel
{
public string Title { get; set; }
public bool IsAuthenticated { get; set; }
}
....
public ActionResult Index()
{
return View(new IndexViewModel()
{
Title = "Index",
IsAuthenticated = UserIsLoggedIn()
});
}
However, to answer your question:
Is there a way in Razor to access a function straight off?
If you are using ASP.NET Membership you can use the IsAuthenticated property on the request e.g.
#Request.IsAuthenticated
Otherwise, you do need to pass this information to the view (whether that be via ViewBag/view model etc.)
Alternatively, you could write your own extension method for Request which would allow you to access it directly in the view:
#Request.UserLoggedIn()
Or even as a HtmlHelper e.g.
public static class HtmlHelperExtensions
{
public static bool UserIsLoggedIn(this HtmlHelper helper)
{
return /* authentication code here */
}
}
Then in your views you can use #Html.UserIsLoggedIn() which I think is what you are after.
use a ViewModel class (your view will then be strongly typed, and you'll be able to use "classic" helpers).
//viewModel class
public class UserStatusViewModel {
public string Title {get;set;}
public bool IsLogged {get;set;
}
//action
public ActionResult Index() {
var model = new UserStatusViewModel{ Title = "Index", IsLogged = TheUser.CheckStatus()};
return View(model);
}
//view
#model UserStatusViewModel
#Html.DisplayFor(m => m.Title)
#Html.DisplayFor(m => m.IsLoggedIn)

ASP.NET MVC Strongly Typed View With DropDownList

Long story short, I'm trying to add a few extra items to ViewData to make my life easier, and its an edge case that doesn't really justify its own model just for this one case. Keep reading for more specific details.
So I have a strongly typed edit view for one of my objects, everything works great until I try to put a dropdownlist on the view with an ID that does not match a property of my class.
I have this
public class MyModel
{
public String Name {get;set;}
public int ID {get;set;}
public MyOtherModel Other {get;set;}
}
public class MyOtherModel
{
public String Name {get;set;}
public int ID {get;set;}
}
I am able to update the Name property.
I'd also like to set the Other.ID property from a DropDownList, but its not letting me do that.
My Controller looks like this
public ActionResult EditView()
{
var da = new DataAccessClass();
var Names = da.ReadActive(); // returns MyOtherModel
var sli = new SelectList(evNames, "ID", "Name");
ViewData["OtherModelNames"] = sli;
return View();
}
My View looks like this:
<p>
<label for="EndTime">Name:</label>
<%= Html.TextBox("Name") %>
<%= Html.ValidationMessage("Name", "*")%>
</p>
<p>
<label for="EndTime">Other Name:</label>
<%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["OtherModelNames"]) %>
<%= Html.ValidationMessage("OtherNameIDList", "*")%>
</p>
I get an error on this line <%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["Names"]) %>
"There is no ViewData item with the key 'OtherNameIDList' of type 'IEnumerable'."
My expectation is that in the controller action that accepts the POST, I will manually use the FormCollection[] to read out that ID and populate MyOtherModel with the correct ID.
In the controller try:
public ActionResult EditView()
{
var da = new DataAccessClass();
var Names = da.ReadActive(); // returns MyOtherModel
var sli = new SelectList(evNames, "ID", "Name");
ViewData.Add("OtherModelNames", new SelectList("ID", "Name", ""));
return View();
}
The in the view
Html.DropDownList("OtherModelNames")
To get the Other.Id in the dropdownlist, just create a static int in the class:
public static int OtherId {get { return this.Other.Id; }}

ASP.Net MVC2 DropDownListFor

I am trying to learn MVC2, C# and Linq to Entities all in one project (yes, I am mad) and I am experiencing some problems with DropDownListFor and passing the SelectList to it.
This is the code in my controller:
public ActionResult Create()
{
var Methods = te.Methods.Select(a => a);
List<SelectListItem> MethodList = new List<SelectListItem>();
foreach (Method me in Methods)
{
SelectListItem sli=new SelectListItem();
sli.Text = me.Description;
sli.Value = me.method_id.ToString();
MethodList.Add(sli);
}
ViewData["MethodList"] = MethodList.AsEnumerable();
Talkback tb = new Talkback();
return View(tb);
}
and I am having troubles trying to get the DropDownListFor to take the MethodList in ViewData. When I try:
<%:Html.DropDownListFor(model => model.method_id,new SelectList("MethodList","method_id","Description",Model.method_id)) %>
It errors out with the following message
DataBinding: 'System.Char' does not contain a property with the name 'method_id'.
I know why this is, as it is taking MethodList as a string, but I can't figure out how to get it to take the SelectList. If I do the following with a normal DropDownList:
<%: Html.DropDownList("MethodList") %>
It is quite happy with this.
Can anyone help?
EDIT: So you are using Entity Framework, yes? In that case with the addition info you put in the comments, you would want to do something like this:
public ActionResult Create()
{
var viewModel = new CreateViewModel(); // Strongly Typed View
using(Entities dataModel = new Entities()) // 'te' I assume is your data model
{
viewModel.Methods = dataModel.Methods.Select(x => new SelectListItem()
{
Text = x.Description,
Value = x.method_id.ToString()
});
}
return View(viewModel);
}
Your strongly typed view model would be:
public class CreateViewModel
{
public string SelectedMethod { get; set; }
public IEnumerable<SelectListItem> Methods { get; set; }
}
Your view code would be:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CreateViewModel>" %>
<%-- Note the Generic Type Argument to View Page! --%>
<%: Html.DropDownListFor(m => m.SelectedMethod, Model.Methods) %>

Categories