Looping Through Properties and accessing its own properties - c#

I am new to C# and Umbraco. Can't figured this simple thing out nor find the solutions
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = null;
}
List<string> test = new List<string>();
var item = CurrentPage.Children.FirstOrDefault();
var count = 0;
foreach (var prop in item.Properties) {
count++;
test.Add(prop.PropertyTypeAlias);
}
<html>
...
</html>
If i count properties it gives correct number of properties but i can't get access its own properties such as "Value", "PropertyTypeAlias" etc. It throw exception reads:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'PropertyTypeAlias'
Thanks in advance.

If you want to access properties of a document type, it's better and easier to do it like this:
#inherits UmbracoTemplatePage
#{
}
<h1>#Model.Content.Name</h1>
#foreach (var item in Model.Content.Children)
{
<h2>#(item.GetPropertyValue<IHtmlString>("bodyText"))</h2>
}
CurrentPage is a dynamic object, whereas Model.Content gets the "current page", but as a strongly-typed IPublishedContent, which means, if you use Visual Studio, you get intellisense and can see which methods you can use.
In the H1-tag, I simply pulled out the current content node's name, in the foreach, I am looping over the current content node's children and displaying their property with alias "bodyText" and datatype "Rich text".
EDIT:
#inherits UmbracoTemplatePage
#{
var child = Model.Content.Children.FirstOrDefault();
var properties = new List<string>();
foreach (var item in child.Properties)
{
properties.Add(item.PropertyTypeAlias);
}
}
#foreach (var item in properties)
{
<h1>#item</h1>
}

Related

How do I get my model into my view using C#?

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>

Set var in foreach to use later

I'm trying to set a value in a foreach but i get the error that it dosent exist in the current contect.
Here is my code;
#{
string sUsr = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToLower();
var db = Database.Open("SQLServerConnectionString");
var selectUser = "SELECT * FROM USERS WHERE username = " + #sUsr;
}
#foreach (var userid in db.Query(selectUser))
{
var sReg = userid.userdisplayname;
var sAns = userid.usersign;
var smail = userid.usermail;
}
...some html code etc.
#sReg <---- The name sReg dosent exist in the current context
If i try with the folowing code it works and Hello World is rendered in my webpage
#{ var myMessage = "Hello World"; }
...some html code etc.
#myMessage
Change your code, so that sReg is defined outside the scope of the foreach loop. You can do this like:
var sReg;
#foreach (var userid in db.Query(selectUser))
{
sReg = userid.userdisplayname;
var sAns = userid.usersign;
var smail = userid.usermail;
}
You can now use the (last) value of sReg outside the loop's body.
Variables defined in code only have a limited area in which they are available, which is commonly called the "scope" of a variable.
Read this article to learn more about scope in C#.
Please be also aware of the fact that you may get multiple results from your query (unless you are selecting with top 1 or such). In that case, your sReg variable would only contain the value of the last iteration, which may not be desirable for you. In this case, a List could come to the rescue: http://www.dotnetperls.com/list
sReg in this context only applied inside your foreach loop.
The reason you're getting the doesn't exist in current context error is because it's not in scope.
If you wanted to proceed and do something with your var sReg you would have to perform whatever operation you would like to do within the loop, or declare it outside if need be.
Hope this helps

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

Loop model data and list it out

I am trying to loop through data that is passed to my view in a model object. I want to list out the property name and the property value of each of the model properties, even if they are null. I have been at this for a few hours and have tried googling it but cannot get any good examples that work.
I got this to list out all of the properties of the current object, however cannot get the values:
#model List<object>
#foreach (var obj in Model)
{
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
string name = null;
var value = ""
try
{
name = property.Name;
value = property.GetType().GetProperty(property.Name).GetValue(property, null).ToString();
}
catch (Exception e)
{
<p>#e</p>
}
finally
{
<p>#name - #value</p>
}
}
And the controller code:
RootobjectPlayerData obj = JsonConvert.DeserializeObject<RootobjectPlayerData>(jsonstring);
List<object> list = new List<object>();
list.Add(obj.data.accountinfo);
list.Add(obj.data.accountinfo.statistics);
list.Add(obj.data.accountinfo.statistics.clan);
list.Add(obj.data.accountinfo.statistics.company);
list.Add(obj.data.accountinfo.statistics.all);
list.Add(obj.data.accountinfo.statistics.historical);
list.Add(obj.data.accountinfo.statistics.team);
return View(list);
I am able to do a break point and view all of the data within each of the objects, however I cannot get it to print out on screen.
First of all you are getting the property value incorrectly. You should get the value from the object you have, but not from the type of the property:
value = obj.GetType().GetProperty(property.Name).GetValue(obj, null)
Secondly, try to loop only through data that's not null:
#foreach (var obj in Model.Where(w => w != null))
Try getting the values from i, not x.
try
{
name = x.Name;
// Wrong
// value = x.GetType().GetProperty(x.Name).GetValue(x, null).ToString();
// Correct
value = x.GetValue(i, null).ToString();
}
catch (Exception e)
{
<p>#e</p>
}

concat string var in razor var name

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

Categories

Resources