Rectangle 27 46

Fixed in ASP.NET MVC 4

If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this:

<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>

Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written:

<div class="@myClass">Content</div>

So if @myClass is null, the output is just this:

<div>Content</div>

You don't actually mean ASP.NET 4, you mean ASP.NET MVC 4 which at the time of writing is still in beta - ASP.NET 4 shipped with VS2010 and .NET 4.0 and does not contain conditional attribute rendering.

How do I do that if I want to add a style to other styles. Say if a bool is true then display:none for example. Or do I still need to use that ugly conditional?

@ppumkin I did it like this; var trstyle = index == 0 ? "display: none;" : null;, then in the tr itself I do <tr style="@trstyle">, which makes the first row hidden (index == 0). The output is simply <tr> for the other rows. Worked beautifully. +1.

asp.net mvc - How to concisely create optional HTML attributes with ra...

asp.net-mvc razor viewengine
Rectangle 27 46

Fixed in ASP.NET MVC 4

If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this:

<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>

Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written:

<div class="@myClass">Content</div>

So if @myClass is null, the output is just this:

<div>Content</div>

You don't actually mean ASP.NET 4, you mean ASP.NET MVC 4 which at the time of writing is still in beta - ASP.NET 4 shipped with VS2010 and .NET 4.0 and does not contain conditional attribute rendering.

How do I do that if I want to add a style to other styles. Say if a bool is true then display:none for example. Or do I still need to use that ugly conditional?

@ppumkin I did it like this; var trstyle = index == 0 ? "display: none;" : null;, then in the tr itself I do <tr style="@trstyle">, which makes the first row hidden (index == 0). The output is simply <tr> for the other rows. Worked beautifully. +1.

asp.net mvc - How to concisely create optional HTML attributes with ra...

asp.net-mvc razor viewengine
Rectangle 27 5

The HttpContext, in the ControllerContext is null because it is not set when the controller is created. The contructor of the controller does not assign this property, so it will be null. Normally, the HttpContext is set to the HttpContext of the ControllerBuilder class. Controllers are created by the ControllerBuilder class, followed by the DefaultControllerFactory. When you want to create your own instance of a controller, you can use the ExecuteMethod of the controller with your own ControllerContext. You don't want to do that is a real application. When you get some more experience with the framework you will find the appropriate method to do want you want. When you need ControllerContext in Unit test, you can use a mocking framework to mock the ControllerContext or you can class faking it.

You can find a model of the request flow in asp.net mvc on this blog.

When your new to Asp.net mvc, it's worth the effort to download the source code and read an trace the route how a request is processed.

HttpContext on instances of Controllers are null in ASP.net MVC - Stac...

asp.net-mvc httpcontext
Rectangle 27 61

public new HttpContextBase HttpContext {
    get {
        HttpContextWrapper context = 
            new HttpContextWrapper(System.Web.HttpContext.Current);
        return (HttpContextBase)context;                
    }
}

I'm not sure if the HttpContext being null is the desired behavior, but this will fix it in the meantime for me.

Thank you so much for deciphering the new way of working between the two types. I had an old class I was trying to use from an MVC controller that consumed an HttpContext object. Now I have a class that consumes an HttpContextBase object with a constructor overload that will convert between HttpContext and HttpContextBase using the HttpContextWrapper constructor you mentioned.

+1 This is a wonderful snippet! I added to it a bit though. I wrapped your wrapper with a ContextHelper class which exposes only the properties I need out of your underlying HttpContext proeprty to allow me to then create a mock of my ContextHelper. StructureMap then allows me to swap what I need in and out. Then I created a WebSite object to act as a view API which is exposed off of all sorts of base classes for views, controllers, etc. I will have to mention this in my book (ASP.NET MVC Cookbook) if you don't mind: groups.google.com/group/aspnet-mvc-2-cookbook-review

HttpContext on instances of Controllers are null in ASP.net MVC - Stac...

asp.net-mvc httpcontext
Rectangle 27 24

Controllers are not designed to be created manually like you're doing. It sounds like what you really should be doing is putting whatever reusable logic you have into a helper class instead.

Brad, do you have somewhere that can help with understanding MVC design and best practices? MVC has been cool so far, but most examples I've found aren't very complex. They only go over the simple instances like updating a single record.

Brad, I have the same issue, and this is also coming from a helper class, just like you recommended. I tried the fix provided by Hugoware (below), and that fixed it. Is this the proper way to do this?

HttpContext on instances of Controllers are null in ASP.net MVC - Stac...

asp.net-mvc httpcontext
Rectangle 27 9

Its null because your model contains a property named gl_code and you have also named the parameter for your model gl_code in the POST method.

Change the name of one or the other and the model will bind correctly.

What is happening internally is that the form submits a name/value pair for each successful form control, in your case gl_code=someValue. The DefaultModelBinder first initializes a new instance of your model. It then reads the form values and finds a match for the property in your model and sets it to someValue. But it also finds a match in the method parameters and tries set the value of the parameter to someValue, which fails (because you cannot do gl_code gl_code = "someValue";) and the model becomes null.

Asp.Net MVC: Why is my view passing NULL models back to my controller?...

asp.net-mvc
Rectangle 27 325

Andrew I think the problem you are getting is a result of the RenderPartial method using the calling (view)'s model to the partial view when the model you pass is null.. you can get around this odd behavior by doing:

<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary()); %>

I get why they support null model and passing the pages Model but couldn't they have handled that by overloading. @Html.Render("donkeys") is different than @Html.Render("donkeys", couldbenull)

I found that with this solution my ValidationSummary in my partial view did not work because the ViewData of the primary model was lost in the partial view. I used the answer given here stackoverflow.com/a/12037580/649497 to solve this.

You should pass along the existing ViewData: new ViewDataDictionary(ViewData)

asp.net mvc - renderpartial with null model gets passed the wrong type...

asp.net-mvc renderpartial
Rectangle 27 325

Andrew I think the problem you are getting is a result of the RenderPartial method using the calling (view)'s model to the partial view when the model you pass is null.. you can get around this odd behavior by doing:

<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary()); %>

I get why they support null model and passing the pages Model but couldn't they have handled that by overloading. @Html.Render("donkeys") is different than @Html.Render("donkeys", couldbenull)

I found that with this solution my ValidationSummary in my partial view did not work because the ViewData of the primary model was lost in the partial view. I used the answer given here stackoverflow.com/a/12037580/649497 to solve this.

You should pass along the existing ViewData: new ViewDataDictionary(ViewData)

asp.net mvc - renderpartial with null model gets passed the wrong type...

asp.net-mvc renderpartial
Rectangle 27 8

Its null because your model contains a property named gl_code and you have also named the parameter for your model gl_code in the POST method.

Change the name of one or the other and the model will bind correctly.

What is happening internally is that the form submits a name/value pair for each successful form control, in your case gl_code=someValue. The DefaultModelBinder first initializes a new instance of your model. It then reads the form values and finds a match for the property in your model and sets it to someValue. But it also finds a match in the method parameters and tries set the value of the parameter to someValue, which fails (because you cannot do gl_code gl_code = "someValue";) and the model becomes null.

Asp.Net MVC: Why is my view passing NULL models back to my controller?...

asp.net-mvc
Rectangle 27 7

After logging in (and redirecting to another page), the IPrincipal.IIdentity should be a ClaimsIdentity. You can try this:

var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
    // the principal identity is a claims identity.
    // now we need to find the NameIdentifier claim
    var userIdClaim = claimsIdentity.Claims
        .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

    if (userIdClaim != null)
    {
        var userIdValue = userIdClaim.Value;
    }
}

This should work for you. If you still unable to get the id then you have to redirect to another page before the server will write the authentication cookie to the browser.

Or Another approach is this :

switch (result)
{
    case SignInStatus.Success:
       ApplicationUser user = UserManager.FindByName(model.UserName);
       string UserId = user.Id;
       returnUrl = CheckUserRoleAndRedirect();
       return RedirectToLocal(returnUrl);
}

is there a way to use identity to get userid before redirection?

string userId = User.Identity.GetUserId();

c# - ASP.NET MVC - Login Success, but userId returns null - Stack Over...

c# asp.net-mvc asp.net-mvc-5 asp.net-identity identity
Rectangle 27 14

Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

Simply adding it won't work since "Session" should have already been defined in the machine.config.

Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...

sessionKey may be changing, you probably only need to do:

HttpContext.Current.Session["CurrentUser"]

Or the session may be expiring, check the timeout:

Or you may be setting the session value from somewhere else, normally i control access to Session/Context object through one property

static readonly string SESSION_CurrentUser = "CurrentUser";

public static SiteUser Create() {     
 SiteUser.Current = new SiteUser();      
 return SiteUser.Current;
}

public static SiteUser Current {     
 get {         
  if (HttpContext.Current.Session == null || HttpContext.Current.Session[SESSION_CurrentUser] == null) {             
   throw new SiteUserAutorizationExeption();         
  }          
  return HttpContext.Current.Session[SESSION_CurrentUser] as SiteUser;     
 } 
 set {
  if (!HttpContext.Current.Session == null) {
   HttpContext.Current.Session[SESSION_CurrentUser] = value;
  }
 }
}

Thank you, I have tried all of what you are suggesting here, but still nothing.

ASP.NET MVC - Session is null - Stack Overflow

asp.net asp.net-mvc-3 session
Rectangle 27 4

Add the claim in ClaimsIdentity:

public class ApplicationUser : IdentityUser
{
    ...

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("DisplayName", DisplayName));
        return userIdentity;
    }
}
public static class IdentityExtensions
{
    public static string GetDisplayName(this IIdentity identity)
    {
        if (identity == null)
        {
            throw new ArgumentNullException("identity");
        }
        var ci = identity as ClaimsIdentity;
        if (ci != null)
        {
            return ci.FindFirstValue("DisplayName");
        }
        return null;           
    }
}
User.Identity.GetDisplayName()

This seems promising... where do you normally place your IdentiyExtensions method? In the IdentityModels.cs? Or would you create a new file with certain name convention for it?

I would create a new file with name "IdentityExtensions.cs", probably inside a folder named "Helpers"

return claim.FindFirst("DisplayName")
return claim.FindFirst("DisplayName").ToString().Substring(("DisplayName: ").Length);
claim.FindFirst("DisplayName")
Claim
return
string
Substring
DisplayName: myname
myname

@Ian you are correct about returning string. I updated the the extension method.

I do not find the FindFirstValue method (there isn't one). Do I miss any reference? Thanks for the update - I accepted your answer anyway, since it already sufficiently points to the right answer. ;)

c# - How to Get Custom Property Value of the ApplicationUser in the AS...

c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity
Rectangle 27 4

Add the claim in ClaimsIdentity:

public class ApplicationUser : IdentityUser
{
    ...

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("DisplayName", DisplayName));
        return userIdentity;
    }
}
public static class IdentityExtensions
{
    public static string GetDisplayName(this IIdentity identity)
    {
        if (identity == null)
        {
            throw new ArgumentNullException("identity");
        }
        var ci = identity as ClaimsIdentity;
        if (ci != null)
        {
            return ci.FindFirstValue("DisplayName");
        }
        return null;           
    }
}
User.Identity.GetDisplayName()

This seems promising... where do you normally place your IdentiyExtensions method? In the IdentityModels.cs? Or would you create a new file with certain name convention for it?

I would create a new file with name "IdentityExtensions.cs", probably inside a folder named "Helpers"

return claim.FindFirst("DisplayName")
return claim.FindFirst("DisplayName").ToString().Substring(("DisplayName: ").Length);
claim.FindFirst("DisplayName")
Claim
return
string
Substring
DisplayName: myname
myname

@Ian you are correct about returning string. I updated the the extension method.

I do not find the FindFirstValue method (there isn't one). Do I miss any reference? Thanks for the update - I accepted your answer anyway, since it already sufficiently points to the right answer. ;)

c# - How to Get Custom Property Value of the ApplicationUser in the AS...

c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity
Rectangle 27 154

The way I solved this is was adding a null to the fourth parameter before the anonymous declaration (new {}) so that it uses the following method overload: (linkText, actionName, controllerName, routeValues, htmlAttributes):

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" })

This is the best answer if you're not linking between Areas. If you need to specify the area for the link, you would need to specify the routeValues with the controller and the area to keep the Length property from showing up in the URL.

routeValues
Html.ActionLink("About", "About", "Home", new {@area = "Admin"}, new { hidefocus = "hidefocus" })

@epiplon, the reason I specify the controller like that is because if you ever don't include htmlAttributes as the last argument of ActionLink, MVC will include a weird Length=x parameter at the end of the URL. For instance, put this on a page, then view the source of your page, and you'll see what I mean: @Html.ActionLink("About", "About", "Home", new { area = "Admin" }, new { hidefocus = "hidefocus" }) @Html.ActionLink("About", "About", "Home", new { area = "Admin" }) But if you put the controller entry in the routeValues, it will never put Length=x in the URL.

asp.net mvc - Why does Html.ActionLink render "?Length=4" - Stack Over...

asp.net-mvc
Rectangle 27 154

The way I solved this is was adding a null to the fourth parameter before the anonymous declaration (new {}) so that it uses the following method overload: (linkText, actionName, controllerName, routeValues, htmlAttributes):

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" })

This is the best answer if you're not linking between Areas. If you need to specify the area for the link, you would need to specify the routeValues with the controller and the area to keep the Length property from showing up in the URL.

routeValues
Html.ActionLink("About", "About", "Home", new {@area = "Admin"}, new { hidefocus = "hidefocus" })

@epiplon, the reason I specify the controller like that is because if you ever don't include htmlAttributes as the last argument of ActionLink, MVC will include a weird Length=x parameter at the end of the URL. For instance, put this on a page, then view the source of your page, and you'll see what I mean: @Html.ActionLink("About", "About", "Home", new { area = "Admin" }, new { hidefocus = "hidefocus" }) @Html.ActionLink("About", "About", "Home", new { area = "Admin" }) But if you put the controller entry in the routeValues, it will never put Length=x in the URL.

asp.net mvc - Why does Html.ActionLink render "?Length=4" - Stack Over...

asp.net-mvc
Rectangle 27 37

In C# it also works with a null as the 4th parameter.

@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC? - Stack ...

css asp.net-mvc vb.net html-helper
Rectangle 27 68

Andrei is right - it is null because when running under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class. If you want a better understanding of the lifecycle you can either pull down the ASP.NET MVC framework (the source is available), or refer to: this page

If you need to access the Session then one way would be to override the "OnActionExecuting" method and access it there, as it will be available by that time.

However, as Andrei is suggesting, if your code is reliant on the Session then it could potentially be difficult to write unit tests, so perhaps you could consider wrapping the Session in a helper class which can then be swapped out for a different, non-web version when running under unit tests, therefore de-coupling your controller from the web.

I don't sure this is proper statement about HttpContext. It actually constructed right at start of entire flow. You can read a bit about detailed flow here beletsky.net/2011/06/inside-aspnet-mvc-route-to-mvchanlder.html or you can use reflector and find yourself when httpContext have been instantiated - its around line 1556 in httpruntime.cs.

@AlexeyShcherbak It may be constructed already - OP is about whether it has been set on the MVC controller's Session property. i.e. public HttpSessionStateBase Session { get; } on System.Web.Mvc.Controller These are different things.

Session null in ASP.Net MVC Controller Constructors - Stack Overflow

asp.net-mvc session
Rectangle 27 6

I finally solved it after a lot of tries. The error message is wrong, it comes from the database and means that username field is null but the database requires it.

Make sure you send the db the user name like that for example:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Hometown = model.Hometown };

And make sure that the database is up to date before that by running update-database.

asp.net mvc - UserManager.AddPasswordAsync() returns "Name cannot be n...

asp.net-mvc asp.net-identity
Rectangle 27 27

I found the solution. You have to add and remove the SessionStateModule:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

I have no idea why Microsoft doesn't add this to the web.config of the project template?

Never saw this need to remove and add. Might be some particularity of MVC4 + IIS7... It worked for me! +1

iis 7 - The Session object is null in ASP.NET MVC 4 webapplication onc...

asp.net-mvc-4 iis-7
Rectangle 27 27

I found the solution. You have to add and remove the SessionStateModule:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

I have no idea why Microsoft doesn't add this to the web.config of the project template?

Never saw this need to remove and add. Might be some particularity of MVC4 + IIS7... It worked for me! +1

iis 7 - The Session object is null in ASP.NET MVC 4 webapplication onc...

asp.net-mvc-4 iis-7