Using If statement in a MVC Razor View - asp.net-mvc-3

In the following code,
If I use "#If" statement ,I get the following compile code error as " The name 'grid' does not exist in the current context.
#if (Model.SModel != null)
{
#{
WebGrid grid = new WebGrid(Model.SModel);
}
}
else
{
}
#grid.GetHtml()
,
But the code compiles without the "If" statement.For example
#{
WebGrid grid = new WebGrid(Model.SModel);
}
#grid.GetHtml().
What is the syntactical error in using If else statement

grid isn't declared outside of the scope of your if statment.
Try this instead:
#if (Model.SModel != null) {
WebGrid(Model.SModel).GetHtml()
}

I would try this:
#if (Model.SModel != null)
{
WebGrid grid = new WebGrid(Model.SModel);
grid.GetHtml()
}
else
{
}

You do not need to use #{} inside #if. Write like this:
#if (Model.SModel != null)
{
WebGrid grid = new WebGrid(Model.SModel)
}

Related

IF condition inside for loop in c#.net

In below code, if(_drone["CODE"] =="zen") inside the for loop is not working,eventhough _drone["code"] contain zen.
Only those records with value zen .nedd to be added to_dr (_abc.rows.ans(_dr)
public DataTable InitInGroup(DataTable _dtdoctor, string _Folio, string _IsCom = "No", string _CODE = "")
{
DataTable _abc = GetDoc("~", "~", "~", "~");
if (_dtdoctor != null)
{
foreach (DataRow _drone in _dtdoctor.Rows)
{
if (_drone["CODE"] == "zen"
Edit
Not working with the one you mentioned .As above another scenario stated below.I want to compare the session value with the database value
foreach (DataRow dr28 in _DTU_ABC.Rows)
{
string ss = HttpContext.Current.Session["ADMIN"].ToString();
IF (dr28[_CODE].ToString == ss)
{
cmd28.Parameters.Clear();
OracleHelper.CreateParameter(ref cmd28, ref param28, "#NUMBER", DbType.String, ParameterDirection.Input, dr28["Number"].ToString());
OracleHelper.CreateParameter(ref cmd28, ref param28, "#SITECODE", DbType.String, ParameterDirection.Input, dr28["CODE"].ToString());
cmd28.ExecuteNonQuery();
}
}
_drone["CODE"] returns an object. Try this instead:
if (_drone["CODE"].ToString() == "zen")

How do I Get Full Html Field Name for an item in a list on my model at controller level?

*First Post
I have a JQuery error handler for my Ajax posts that I must use, it appends an error to the html based on the field name for that element like this
$(document).ready(function () {
function myHandler(e, error) {
var tag = "";
if (error.Success == true) { $('.field-validation-error').remove(); return; } // if success remove old validation and don't continue
if (error.Success == false) { $('.field-validation-error').remove(); } // if success remove old validation and continue
for (i = 0; i < error.Errors.length; i++) {
var t = error.Errors[i];
//get error key and assign it to id
tag = t.Key;
//clear down any existing json-validation
for (j = 0; j < t.Value.length; j++) {
//this part assumes that our error key is the same as our inputs name
$('<span class="field-validation-error">' + t.Value[j].ErrorMessage + '</span>').insertAfter('input[name="' + tag + '"], textarea[name="' + tag + '"], select[name="' + tag + '"], span[name="' + tag + '"]');
}
}
}
$.subscribe("/******/errors", myHandler);
});
This works perfectly out of the box with our fluent validation setup until I try to add a custom modelstate error at controller level like so:
foreach (var item in model.Locations)
{
var cityRepos = new CityRepository(NhSession);
var cityItem = cityRepos.GetAll().FirstOrDefault(o => o.Country.Id == item.CountryID && o.Name == item.City);
if (cityItem == null)
item.City
ModelState.AddModelError("City", string.Format(#"The city ""{0}"" was not found, please ensure you have spelt it correctly. TODO: add a mail to link here with city not found subject", item.City));
}
the problem is that the modelstate error needs to be attached to the html field name not my magic string "City". The html name property is MVC Generated and looks something like this:
name="Locations[0].City"
I have encountered this problem in a html helper before and used the method:
.GetFullHtmlFieldName(
ExpressionHelper.GetExpressionText(propertySelector)
);
which resolved my problem in that case.
My question is can I use this method on my model property in an MVC post action to obtain the html name property it has come from?
Thanks in advance
ok so it's not ideal but I have implemented this Helper method until I can find a better solution that doesn't involve magic strings:
public static class ModelStateErrorHelper
{
public static string CreateNameValidationAttribute(string collectionName, int index, string propertyName)
{
string template = "{0}[{1}].{2}";
return string.Format(template, collectionName, index.ToString(), propertyName);
}
}

MVC3 Multiple Conditions in where Clause

I have the following in my Controller
var workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);
ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name));
and this in my view
#{
//var carts = Model.Carts.Where(x => x.Username.Equals(User.Identity.Name));
var carts = ViewBag.Enrollments;
var timeSlot = Model.TimeSlot;
}
#{
foreach (var item in carts)
{
if (item != null)
{
if (timeSlot == item.Workshop.TimeSlot)
{
<h3>#timeSlot</h3>
}
}
else
{
<h3>Does not Exist</h3>
}
}
}
each time ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name)); returns no results, I get an error saying System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first. and this line is highlighted
if (timeSlot == item.Workshop.TimeSlot)
Try calling .ToList() in the controller to eagerly fetch the results:
ViewBag.Enrollments = registerDB
.Carts
.Where(x => x.Username.Equals(User.Identity.Name))
.ToList();
You are checking that item != null but not that item.Workshop != null before trying to use it. It would appear that is perhaps the error, but why it's raising InvalidOperationException rather than NullReferenceException I don't know.
Try:
if (item != null && item.Workshop != null)
{
if (timeSlot == item.Workshop.TimeSlot)
{
<h3>#timeSlot</h3>
}
}
Could you put the single call in your model:
workshops workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);
And then in your controller set the ViewBag:
try
{
ViewBag.Enrollments = workshop.Carts.Where(x => x.Username.Equals(User.Identity.Name));
}
catch
{
ViewBag.Enrollments = "There are no results";
}

Adobe Flex 4 Tree Treelistdata

Is it possible to find if a treeListData is having a sibling or not. In adobe Flex 4 and actionscript 3
Yes, you could check the item property of the TreeListData instance inside an ItemRenderer and either:
use item as ITreeDataDescriptor and check the hasChildren property
use item as your custom class and possibly check the length of your children collection (depending on your data-model).
Example code:
protected function dataChangeHandler(event:FlexEvent):void
{
var node:TreeNode = treeListData as TreeNode;
if(node != null)
{
if(node.children != null && node.children.length > 0)
{
hasChildren = true;
return;
}
}
hasChildren = false;
}
Hope this answers your question.

DataTable that has List<string> in it

I'm using Linq to return data from an XML file to a DataTable and that works. But now I'm trying to modify the code to loop through the DataTable. I created a custom class to model the data and have a List in my model. When I loop through the DataTable to display records it displays System.Collections.Generic.List`1[System.String] instead of the actual data. I'm not sure what to search to find the answer.
Snippet:
foreach (DataRow row in tbl.Rows)
{
myList = row["myList"] + ", " + myList;
}
The myList column is the List. I hope this makes sense.
Edited:
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
hobbiesList = (List<string>)row["hobbies"];
foreach (var item in hobbiesList)
{
hobbies.Add(item.ToString());
}
hobby = string.Join(", ", hobbies.ToArray());
hobbies.Clear();
I had to do the above to get it to work. I then add hobby to my output array.

Resources