Rectangle 27 673

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 657

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 657

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 673

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 673

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 17

ASP.Net MVC

This was a great solution for us to automate displaying a versioning based on our SVN revisions. One advantage is that it doesn't require a call to your SVN server.

Thanks @cacho, fixed - it was a server fault [sic] ;o)

.net - How do I sync the SVN revision number with my ASP.NET web site?...

.net asp.net svn versioning
Rectangle 27 12

What is the Asp.Net MVC Membership Starter Kit?

The starter kit currently consists of two things:

  • A sample website containing the controllers, models, and views needed to administer users & roles.
  • A library that provides testable interfaces for administering users & roles and concrete implementations of those interfaces that wrap the built-in Asp.Net Membership & Roles providers.

Out of the box, the starter kit gives you the following features:

  • Change a User's Roles

It looks like it's based on MVC 2, and I'm not sure it works on anything else. You do have the code though, so it shouldn't be hard to re-use this in MVC 3 or Web Forms.

In the mean time, I forked the project and updated everything to MVC 3 razor. I also packaged the views up into a Portable Area (mvcContrib).

You can find the fork here:

Admin pages to manage asp.net membership provider & Role management - ...

asp.net asp.net-membership membership membership-provider
Rectangle 27 78

ASP.NET MVC 5 Empty Project
Add..
New Scaffolded Item...
MVC
MVC 5 Dependencies
Full dependencies

This will add a default layout (Views\Shared\_Layout.cshtml), Content folder, Scripts folder with bootstrap, jquery, modernizr, etc, and other things the Web Application template creates.

This worked great for me! Only small thing is that it didn't add the default Home controller and associated View, but that's no biggie. Thanks so much!

<add namespace="System.Web.Optimization"/>
<namespaces>
Views/web.config

Thanks Sean. My issue was solved.

Web Platform Installer
ASP.NET and Web Tools 2012.2

No ASP.NET MVC 5 Web Application Template on VS 2012? - Stack Overflow

asp.net-mvc asp.net-mvc-4 visual-studio-2012 visual-studio-2013 asp.net-mvc-5
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 166

The main advantages of ASP.net MVC are:

The main advantage of ASP.net Web Form are:

Regarding SoC, people can mess up with it just like they use to on webforms, by writing "fat" controllers with lots of business logic or even data access code in it. So I would say SoC is something that must be provided by the coder, the fw can't help.

@ rodbv: Very true, but MVC does sort of push you in the right direction, or at least doesn't make you jump through hoops to do so. So maybe that point should read something like 'makes SoC easier to implement'

How does it "Enable Test Driven Development" over any other method ? I'm also confused how it allows RESTful urls when HttpContext.RewritePath Method (String) has been around since .NET 2.0 ?

While these points are mostly accurate for the MVC side, a lot of them are being integrated into WebForms now.

Biggest advantage to using ASP.Net MVC vs web forms - Stack Overflow

asp.net asp.net-mvc
Rectangle 27 33

ViewBag.Message = "Welcome to ASP.NET MVC!";

On the Index View I add the partial view:

@Html.Partial("ViewName")

And on the partial view I render the message:

@ViewBag.Message

Works perfectly. What else did you do? Might be a typing mistake?

I've found that if you use @Html.Partial("ViewName", Model) then the rest of the viewbag will not be available.

Are you sure? For me this is only the case when you specify explicit viewData. Like this: @Html.Partial("ViewName", Model, ViewData) otherwise the ViewBag is fully accessible.

I know this is a bit old, but for future reference, I solved this by using ViewContext.Controller.ViewBag.Property. Of course this means that the ViewBag property you are trying to access was set in the controller, but I think that is a common enough case.

I know we should not be saying thanks but this was upsetting me until I read TehOne's comment. You saved my life TehOne :P!!

This only ever happens to be when I load a partial within a partial. @TehOne's solution worked for me

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Can't access ViewBag in a partial view in ASP.NET MVC3 - Stack Overflo...

asp.net-mvc-3 viewbag
Rectangle 27 33

ViewBag.Message = "Welcome to ASP.NET MVC!";

On the Index View I add the partial view:

@Html.Partial("ViewName")

And on the partial view I render the message:

@ViewBag.Message

Works perfectly. What else did you do? Might be a typing mistake?

I've found that if you use @Html.Partial("ViewName", Model) then the rest of the viewbag will not be available.

Are you sure? For me this is only the case when you specify explicit viewData. Like this: @Html.Partial("ViewName", Model, ViewData) otherwise the ViewBag is fully accessible.

I know this is a bit old, but for future reference, I solved this by using ViewContext.Controller.ViewBag.Property. Of course this means that the ViewBag property you are trying to access was set in the controller, but I think that is a common enough case.

I know we should not be saying thanks but this was upsetting me until I read TehOne's comment. You saved my life TehOne :P!!

This only ever happens to be when I load a partial within a partial. @TehOne's solution worked for me

Can't access ViewBag in a partial view in ASP.NET MVC3 - Stack Overflo...

asp.net-mvc-3 viewbag
Rectangle 27 93

[RequireHttps]
public ActionResult Login()
{
   return View();
}

Though, the order parameter is worth noting, as mentioned here.

You can also do this on the controller level. Better yet, if you want the entire application to be SSL, you can create a base controller, extend it for all controllers, and apply the attribute there.

Alternatively you can add it is a global filter MVC3 in Global.asax GlobalFilters.Filters.Add(new RequireHttpsAttribute());

SSL pages under ASP.NET MVC - Stack Overflow

asp.net asp.net-mvc ssl https
Rectangle 27 93

[RequireHttps]
public ActionResult Login()
{
   return View();
}

Though, the order parameter is worth noting, as mentioned here.

You can also do this on the controller level. Better yet, if you want the entire application to be SSL, you can create a base controller, extend it for all controllers, and apply the attribute there.

Alternatively you can add it is a global filter MVC3 in Global.asax GlobalFilters.Filters.Add(new RequireHttpsAttribute());

SSL pages under ASP.NET MVC - Stack Overflow

asp.net asp.net-mvc ssl https
Rectangle 27 14

Type clashes as per Asp.net MVC team

You can always provide a custom controller factory that will resolve these classes differently. And I do agree that controllers need no Controller type name appending because after all they're just like any other class. Their OOP ancestor type defines them as controllers anyway (IController, Controller...)

Although it may have something to do with Visual Studio. Similar to Attribute classes. Maybe Visual Studio wouldn't provide additional context menu items to classes that don't end with Controller. When being in controller action you can easily navigate (or create) to the matching view.

So say the experts and I do agree. There are other conventions like these in .net framework as well but people don't complain about them.

Think of collections, dictionaries, attributes, lists and other types that also use similar suffixes without particular reason. They'd work either way, but they're much easier recognisable by their users - developers - who instinctively know how they should work and when to use them.

Imagine having a ProductController that likely handles Product application model entity instances. By not having the controller naming convention, we'd have two types with the same name hence would always have to provide namespaces to distinguish between the two. But because we do have this convention this is not necessary and no type clashes occur.

public class ProductController : Controller
{
    public ActionResult Index()
    {
        // we'd have to distinguish this Product type here
        IEnumerable<Product> result = GetProducts();
        return View(result);
    }
    ...
}

I agree that conventions are good and they are present throughout .NET for a reason, but most conventions aren't enforced, I just find it a strange decision to enforce the convention in this case as there is absolutely no need. A dictionary, list etc will be used throughout an application, whereas in 99.9999999% of the times controllers are going to be in the same place.

@dormisher: that is true, but with those 99.9% of times it doesn't hurt to have convention but the rest 0.1% benefits lots by them. So let's have a convention.

@dormisher: Even more important: as Asp.net MVC team says, this convention has been introduced, because you may have a ProductController class that will likely be handling Product application model class. If there was no controller convention, you'd have type name clashes and would always have to provide namespaces to distinguish between the two. By having Controller suffix on controller types, this is not necessary.

also I take your point about the type clashes, that is a good enough reason I think

asp.net mvc - Why do MVC controllers have to have the trailing 'Contro...

asp.net-mvc
Rectangle 27 14

Type clashes as per Asp.net MVC team

You can always provide a custom controller factory that will resolve these classes differently. And I do agree that controllers need no Controller type name appending because after all they're just like any other class. Their OOP ancestor type defines them as controllers anyway (IController, Controller...)

Although it may have something to do with Visual Studio. Similar to Attribute classes. Maybe Visual Studio wouldn't provide additional context menu items to classes that don't end with Controller. When being in controller action you can easily navigate (or create) to the matching view.

So say the experts and I do agree. There are other conventions like these in .net framework as well but people don't complain about them.

Think of collections, dictionaries, attributes, lists and other types that also use similar suffixes without particular reason. They'd work either way, but they're much easier recognisable by their users - developers - who instinctively know how they should work and when to use them.

Imagine having a ProductController that likely handles Product application model entity instances. By not having the controller naming convention, we'd have two types with the same name hence would always have to provide namespaces to distinguish between the two. But because we do have this convention this is not necessary and no type clashes occur.

public class ProductController : Controller
{
    public ActionResult Index()
    {
        // we'd have to distinguish this Product type here
        IEnumerable<Product> result = GetProducts();
        return View(result);
    }
    ...
}

I agree that conventions are good and they are present throughout .NET for a reason, but most conventions aren't enforced, I just find it a strange decision to enforce the convention in this case as there is absolutely no need. A dictionary, list etc will be used throughout an application, whereas in 99.9999999% of the times controllers are going to be in the same place.

@dormisher: that is true, but with those 99.9% of times it doesn't hurt to have convention but the rest 0.1% benefits lots by them. So let's have a convention.

@dormisher: Even more important: as Asp.net MVC team says, this convention has been introduced, because you may have a ProductController class that will likely be handling Product application model class. If there was no controller convention, you'd have type name clashes and would always have to provide namespaces to distinguish between the two. By having Controller suffix on controller types, this is not necessary.

also I take your point about the type clashes, that is a good enough reason I think

asp.net mvc - Why do MVC controllers have to have the trailing 'Contro...

asp.net-mvc
Rectangle 27 131

ASP.NET MVC 4 has Html.IdFor() built in that can return this:

@Html.IdFor(m => m.User.Surname)

How to get the HTML id generated by asp.net MVC EditorFor - Stack Over...

asp.net-mvc asp.net-mvc-2
Rectangle 27 143

return View("../Category/NotFound", model);

It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.

Works in MVC 2, and turned out to be the cleanest solution for an unusual situation I'm dealing with.

it works in mvc1 too

Resharper will report that link as an error but it still works.

Also works in MVC 5. Good one.

Display a view from another controller in ASP.NET MVC - Stack Overflow

asp.net asp.net-mvc views controllers
Rectangle 27 143

return View("../Category/NotFound", model);

It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.

Works in MVC 2, and turned out to be the cleanest solution for an unusual situation I'm dealing with.

it works in mvc1 too

Resharper will report that link as an error but it still works.

Also works in MVC 5. Good one.

Display a view from another controller in ASP.NET MVC - Stack Overflow

asp.net asp.net-mvc views controllers