concat string var in razor var name - c#

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

Related

How to pass query parameter value into HTML.Partial model?

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

session's variables values retrieving in _LayoutPartial in asp.net mvc

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)

Find item from Viewbag.List

My controller code is as follows
ViewBag.Districts = (from a in _dbContext.DISTRICTS
select new ComboItem {
ID = a.DISTRICT_ID,
Name = a.DISTRICT_NAME
}
).ToList();
My Razor View code as follows
#foreach (var dist in ViewBag.Districts)
{
if (item.DISTRICT_ID == dist.ID)
{
#dist.Name
}
}
Is there a way I can find item in ViewBag.Districts like ViewBag.Districts.where(m=>m.ID==item.DISTRICT_ID.
or linq expression so that i can avoid looping.
Anyone helps me greatly appreciated.
Viewbag is dynamic so compiler won't be able to identify its actual Type, so you need explicit type cast like this to work with Enumerable methods:-
((IEnumerable<ComboItem>)ViewBag.Districts).Where(x => x.ID == item.DISTRICT_ID);
I am assuming you want to use this in your View, Also the foreach loop you have posted won't work without explicit casting:-
#foreach (var dist in (IEnumerable<ComboItem>)ViewBag.Districts)
{
if (item.DISTRICT_ID == dist.ID)
{
#dist.Name
}
}

Simple razor templating syntax to include a comma to separate the names

I have the following razor template html, although I can't figure out how to include a comma to separate the names within the markup!? When trying the following code I get ; expected as a compiler error!. I'll also need to remove the last comma as well.
#foreach (People person in Model.People)
{
person.Name,
}
I want: Ted, James, Jenny, Tom
What about string.Join instead of foreach (it even solves the comma after the last item problem):
#String.Join(", ", Model.People.Select(p => p.Name).ToArray())
You can use <text></text> to include literal content in a Razor template. To omit the last comma, I would use a for loop rather than foreach.
#{
var peopleList = Model.People.ToList();
for( int i = 0; i < peopleList.Count; i++ )
{
#peopleList[i].Name
if( i < peopleList[i].Count - 1 )
{
<text>,</text>
}
}
}
As #nemesv points out, if all you are doing is creating and displaying a delimited string, string.Join() is a cleaner way to accomplish this. If you are building more complex markup, you will probably need to use a loop.
You could achieve the result in a compact way using ternary operator
#foreach (People person in Model.People)
{
#person.Name#((person != Model.People.Last()) ? "," : "")
}
An idea for a scenario where you need to do additional "stuff" in the foreach loop than just rendering the display.
// index.cshtml
#{ var lastPerson = Model.People.LastOrDefault(); }
#foreach (People person in Model.People)
{
var display = person != lastPerson ? $"{person.Name}, " : person.Name;
#display
}
Or if you're like me and you want to try to keep comparison and parsing logic out of the view, you can write a simple extension method.
// StringExtensions.cs
public class StringExtensions
{
public static string DisplayAsCommaListItem(
this string str, object currentItem, object lastItem)
{
return currentItem != lastItem ? $"{str}, " : str;
}
}
Then the view code becomes..
// index.cshtml
#{ var lastPerson = Model.People.LastOrDefault(); }
#foreach (People person in Model.People)
{
#person.Name.DisplayAsCommaListItem(person, lastPerson)
}
#foreach (People person in Model.People)
{
person.Name<text>, </text>
}
or better:
string.Join(", ", Model.People.Select(x => x.Name).ToArray())
Try this:
bool firstIteration = true
#foreach (People person in Model.People)
{
if(firstIteration)
{
#: person.Name
}
else
{
#: "," + person.Name
}
firstIteration = false;
}
Try something like
#foreach (People person in Model.People)
{
#person.Name<text>,</text>
}

ASP.NET MVC List All Users

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

Categories

Resources