Sometimes I have to check the existence of a member inside the ViewBag from inside an Mvc View, to see if for any problem the action forgot to assign the member. Inside my Razor View I have:
#if(ViewBag.Utente.Ruolo.SysAdmin)
how can I check that ViewBag.Utente is defined?
You must check all objects are null or not. Utente, Utente.Ruolo and Utente.Ruolo.SysAdmin may be null:
#if (ViewBag.Utente != null)
{
if (ViewBag.Utente.Ruolo != null)
{
if (!string.IsNullOrEmpty(ViewBag.Utente.Ruolo.SysAdmin))
{
//ViewBag.Utente.Ruolo.SysAdmin has value..you can use it
}
}
}
As simple as this:
#if (ViewBag.Utente != null)
{
// some code
}
If you are using MVC4 you can use
#if (ViewBag.Utente != null)
For previous versions take a look at those answers:
Checking to see if ViewBag has a property or not, to conditionally inject JavaScript
You can you use it;
#if (string.IsNullOrEmpty(ViewBag.Utente.Ruolo.SysAdmin))
{
}
But if you want to check your users are confirmed or not, I think it is not a good way..
Related
I am using MVC3, C#, Razor, .NET4
I use a session variable in my Model constructor. Sometimes it can be null, mainly due to recycling of the AppPool. I need to catch the "null" error of the session and ideally redirect to another action ie Error/Index. However I am in model, and I am not sure whether one can redirect out of a model class.
my Code:
try
{
intOrderId = (Int32) System.Web.HttpContext.Current.Session["OrderId"];
intSupplierId = (Int32) System.Web.HttpContext.Current.Session["SupplierId"];
}
catch (Exception e)
{
// Redirect to Error/Index ?????
}
I have a feeling that I may have to set a property in the model to highlight the error, and then have the controller's action inspect this and act accordingly, howowever I have loads of actions that call this model, so I am not wanting to do this. I would rather react to this error in one place.
Many thanks in advance for any help on this.
Rather than using try/catch to handle empty values, why not check before you read?
if(System.Web.HttpContext.Current.Session["OrderId"] != null)
&& System.Web.HttpContext.Current.Session["SupplierId"] != null)
{
intOrderId = (Int32) System.Web.HttpContext.Current.Session["OrderId"];
intSupplierId = (Int32) System.Web.HttpContext.Current.Session["SupplierId"];
}
else
{
//Throw an exception that the controller can catch: NullReferenceException or InvalidCastException.
//Or return a specific value to indicate that an error occured
}
Is it possible to recognize the view/page name from which a form was submitted to Action ?
For example, lets say I have two Views: AddInfo and EditInfo
Both views have a form that I would like to submit to
#Html.BeginForm("SaveInfo","Info")
{
...
}
Inside of the SaveInfo() method I would like to recognize whether the submit/request came from AddInfo or EditInfo view.
public ActionResult SaveInfo(FormCollection collection)
{
if(...I got here from AddInfo View) <----- ?
{
..do something
}
}
Is it possible ?
Thanks
If the Add/Edit forms are at different pages on your site, then you can use Request.UrlReferrer to check where it came from. That is, something like:
bool sourceIsAddForm =
(Request.UrlReferrer.AbsoluteUri.IndexOf("/add", StringComparison.CurrentCultureIgnoreCase) != -1);
I have a single controller that I want to use for CRUD operations on two different entities which implement the same interface. I'd like for Ninject to give it a different repository based on a query string value in the URL (or maybe a different URL, routed to the same controller). Is this possible? How can I do it?
That's usually a design smell but you could define the binding like this:
kernel.Bind<IRepo>().ToMethod(ctx =>
{
var a = HttpContext.Current.Request["a"];
if (a == "b")
{
return new RepoA();
}
return new RepoB();
}).InRequestScope();
The following worked for me, Getting A Specific value from a route
kernel.Bind<IRepo>().ToMethod(ctx =>
{
var a = HttpContext.Current.Request.RequestContext.RouteData.Values["RouteDateValue"]
if (a != null)
{
return new RepoA(a);
}
return new RepoB();
})
I have a Model (BusinessPlaceDetailsViewModel) which has another Model (Hub) inside it.
However if I set my Hub to null it still enters my IF condition, see here:
I have tried loads of different combinations like putting each IF statement inside its own braces.
Why is it entering the If block?
I'm betting that it is a problem with the controller not passing the model down to the view.
If you post the controller code it might be helpful.
Just out of curiosity, can you try this and see if the h1 displays?
#if (!User.Identity.IsAuthenticated)
{
if (Model.Hub == null)
{
<h1>wtf shouldn't have gotten here</h1>
}
else
{
...
}
}
Could you handle your check in the controller first? If not maybe try .Any() with Ling.
#using System.Linq
#if( !Model.Any() )
{
...
}
else
I solved this problem by using the following in the BusinessPlaceDetailsViewModel
public BusinessPlaceDetailsViewModel()
{
Hub = new HubViewModel();
}
I am scratching my head as to why not this isn't working:
#if (Model.Guid != null) { Html.ActionLink("Fil", "GetFile", new { id = Model.DocumentID }); }
The conditional on its own is working as putting som random HTML in there instead of an actionlink works:
#if (Model.Guid != null){<span>Test</span>}
Likewise the actionlink on it's own renders without a problem.
Could anybody clue me in to what is going on here?
You need to put an # sign before the Html.ActionLink.
Like this:
#if (Model.Guid != null) { #Html.ActionLink("Fil", "GetFile", new { id = Model.DocumentID }); }
EDIT: Forgot to add that you don't need the semi colon, but you can leave it in if you want.