I'm trying to show a list of all users but am unsure how to go about this using the MVC model.
I can obtain the list of all users via the Membership.GetAllUsers() method however if I try to pass this to the view from the ActionResult, I'm told that Model is not enumerable.
You have to set the View to accept an object of type MembershipUserCollection
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MembershipUserCollection>" %>
In your action:
public ActionResult GetUsers()
{
var users = Membership.GetAllUsers();
return View(users);
}
then you can write in your view something like:
<ul>
<%foreach (MembershipUser user in Model){ %>
<li><%=user.UserName %></li>
<% }%>
</ul>
In your view page, on top, you need to set the type of the view page. IE:
On the top of your View, in the first line of the markup, you'll see something like this:
Inherits="System.Web.Mvc.ViewPage"
Change that to be:
Inherits="System.Web.Mvc.ViewPage<MembershipUserCollection>"
or whatever the type you're trying to pass to the view. The "Model" object will now be of type MembershipUserCollection which you can safely iterate over.
[Edit] Specifically, what does the view look like (e.g. what's it expecting to get as the model, how are you parsing the collection, etc.)
Can you post some code? I'm doing something similar, but am having no problems.
It sounds like you need to make your view strongly typed view. Have your view derive from ViewPage<MembershipUserCollection> instead of just ViewPage. Another solution is to cast your Model to MembershipUserCollection in your view:
<% var members = (MembershipUserCollection) ViewData.Model %>
<% foreach (MembershipUser user in members) { %>
<%-- Do Stuff with the user --%>
<% } %>
Try asp.net application object
string id = Session.SessionID.ToString();
String[] users = new String[1000];
users = (string[])Application["users"];
int count=0;
for (int d=0;1000 >d ;d++ )
{
if (users == null) { users = new String[1000]; }
count = d;
if (users[d] == null) { break; }
}
users[count] = id;
Application["users"] = users;
string[] usersTable = (string[])Application["users"];
for (int d=0;1000 >d ;d++ )
{
if (usersTable[d] == null) { break; }
Label1.Text += usersTable[d].ToString()+" | ";
add to application object code
Application["users"] = users;
retrive from applicaton object
string[] usersTable = (string[])Application["users"];
this will help you
Related
I have an MVC page (Not .Net Core) which contains the below code
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(1))
The query in the address bar is similar to ..../products/product?id=4
How could i pass in the query value of 4 (or whatever it might be) into the Model.Product(ID) which then calls some code in my database to retrieve that product?
Using a hardcoded value works so im not sure if i should be doing this differently or if there is a better approach?
Finally hopefully this wont make a difference but once i have this working i would like to change the URL to something more friendly i.e. ..../products/product/4
method 1 : get route data in razor view
{
var id = Context.GetRouteData().Values["id"];
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(id))
method 2 : pass id with controller (viewbag or model)
public ActionResult Product(int id){
var model= {
...
Id = id
}
//ViewBag.Id = id;
return View(model)
}
view:
#model ViewModel
{
var id = int.Parse(ViewBag.Id); // alternative sln.
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(Model.Id))
I have been using the below method and it works for me you can also try this
#Html.Action(, , new { #<Parameter_name> = })
Eg:
#Html.Action("DetailsProducts", "CREDITNOTEs", new { #id = Model.ID })
I'm filling values to a session's like following to retrive those in _LayoutPartial view
if (userdata != null)
{
Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });
}
I want to retrive those values in _LayoutPartial View , So I tried somethin like following
<a class="sa">
(#Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName
(#Session["userdata"] as ProjectName.Models.SampleViewModel).LastName
</a>
But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also
You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be
#((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)
I have deserialized my JSON response into an object. What are the next steps? I have a WebAPI controller that I currently working with my JSON object. I need to take this data and move it into a view so that I can connect it to my web components.
I guess I'm confused on if I should iterate through my JSON object in the controller or in the view? I have the following:
var model = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
foreach (var record in Data.rows)
{
foreach (var nestedRecord in record.f)
{
List<string> list = new List<string>();
list.Add(nestedRecord.v);
}
}
return View();
Also, I'm iterating through this model and I cannot return the model in the view since it's outside the scope.
I see two popular options here, depending on how much information you might potentially access from the deserialized object. One, use the MyData.RootObject as your model, and iterate it in the view. This would give you the greatest flexibility if you need to access other properties of the object:
var model = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
return View(model);
In the view (this unordered-list markup is only a sample), you might have:
#model MyData.RootObject
<ul>
#foreach (var record in Model.rows)
{
foreach (var nestedRecord in record.f)
{
<li>#nestedRecord.v</li>
}
}
</ul>
Or, continue as you had planned, but move the list you're populating outside of the for-loops, using the list as the model. This would be the least flexible in terms of rendering your object in the view:
var rootObject = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
List<string> list = new List<string>();
foreach (var record in rootObject.rows)
{
foreach (var nestedRecord in record.f)
{
list.Add(nestedRecord.v);
}
}
return View(list);
And your view in this case (much more concise than the other option):
#model System.Collections.Generic.List<string>
<ul>
#foreach (var record in Model)
{
<li>#record</li>
}
</ul>
I can't find anything to solve my problem in search, and here is my problem:
I'm using ASP.NET MVC 4 and EF 5, I'm trying to get a value from my db, but this db field depends on other var.
In Controller:
public ActionResult Products()
{
ViewBag.lang = "ENG";
DataEntities db = new DataEntities();
ViewBag.Categories = db.Categories;
return View();
}
In Template View:
<ul>
#{
if (ViewBag.Categories != null)
{
foreach (var cat in ViewBag.Categories )
{
<!-- we need in this case "Name_ENG" -->
var title = "Name_" + #ViewBag.lang;
<li>#cat.(title)</li>
<!-- out: cat.ToString() + "(title)" -->
<li>#cat.(#title)</li>
<!-- out: cat.ToString() + "(" + title.ToString() + ")" -->
<li>#cat.#title</li>
<!-- out: cat.ToString() + title.ToString() -->
}
}
}
</ul>
is there a way to get property "Name_ENG" from cat object like #cat.Name_ENG using a string ?
"In this case I'm trying to list al Categories in Products page."
Thanks a lot
No, definitely not in c#. You'd have to use reflection for this to work (and the syntax would be different of course as well).
I think a better option would be to create a method that would retrieve the value based on a string input, like
public T GetValue<T>(string propertyName)
and call that from your view when needed
here is an article from msdn. You can access EF entries properties by name. But at first you need dbContext and second it is wrong to access dbContext from view.
example:
object currentName2 = context.Entry(blog).Property("Name").CurrentValue;
Also, as mentioned in another answer, reflection:
object value = typeof(YourType).GetProperty("PropertyName").GetValue(yourInstance, null);
Try this
<ul>
#{
if (ViewBag.Categories != null)
{
foreach (var cat in ViewBag.Categories )
{
// here you can do something on cat
<text>
<li>#(cat.title)</li>
</text>
}
}
}
</ul>
I personally suggest you to pass the data to the view by parameter. And use #model in the view (strong type view).
I'll explain a quiet better here. I've this method wich returns me some lines of ma table according to a searchstring I informed in my textbox.
public ActionResult Index(string site, string searchString)
{
var user = from m in db.OrderDetails
select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return View(user);
}
In the same class, I've an other method which generate a pdf file (all the backend process is set up in a second project include in the first).
public ActionResult PrintOrders()
{
var user = from m in db.OrderDetails
select m;
return this.ViewPdf("Facture", "PrintView", user);
}
This second method, when it generate my pdf file, displays all the entries of my table. I would like that, when I click on my link (on the same page view wich display my table entries) for generate my pdf file, if I did a search before, I juste have fields that match my searchstring (or site string).
How can I implement it ? There is a way do to it ?
Thanks for your help, and sorry for the title which is maybe not too relevant. Also sorry for my english, hope you'll understand my aim.
EDIT INFORMATIONS
After looking, when I set up my PrintOrders() method like my Index() method as follow :
public ActionResult PrintOrders(string searchString, string username)
{
var user = from m in db.OrderDetails select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return this.ViewPdf("Facture Krys-Group", "PrintView", user);
}
and set my view like this :
#using (Html.BeginForm("PrintOrders", "Historic", FormMethod.Get))
{
Seach by ID : #Html.TextBox("searchString")
Search by Site : #Html.TextBox("site")
<input type="submit" value="Search" /></p>
}
then it works. But I've already the same form in my view for "Index" instead of "PrintOrders". How can I combine both ?
I am not sure I follow you completely but I think you achieve what you are looking for with the use of partial views. The form you mention can be a partial view that gets rendered into the pdf view and like that you really have one form but displayed in both pages. Hopefully I understood what you were after and this helps you.