Rectangle 27 48

in views

hidden field with model and form:

<?php echo $form->hiddenField($model, 'name'); ?>
<?php echo CHtml::hiddenField('name' , 'value', array('id' => 'hiddenInput')); ?>

php - Basic Hidden field in yii - Stack Overflow

php yii field hidden
Rectangle 27 20

The Views - Simple solution

I prototyped a possible solution to this, because it seemed like a fun problem. I hope it's useful to you.

First, the models. I decided to create two 'widgets', one for news, and one for a clock.

public class NewsModel
{
    public string[] Headlines { get; set; }

    public NewsModel(params string[] headlines)
    {
        Headlines = headlines;
    }
}

public class ClockModel
{
    public DateTime Now { get; set; }

    public ClockModel(DateTime now)
    {
        Now = now;
    }
}

My controller doesn't know anything about the views. What it does is returns a single model, but that model has the ability to dynamically fetch the right model as required by the view.

public ActionResult Show(string widgetName)
{
    var selector = new ModelSelector();
    selector.WhenRendering<ClockModel>(() => new ClockModel(DateTime.Now));
    selector.WhenRendering<NewsModel>(() => new NewsModel("Headline 1", "Headline 2", "Headline 3"));
    return PartialView(widgetName, selector);
}

Delegates are used so that the correct model is only created/fetched if it is actually used.

The ModelSelector that the controller uses is pretty simple - it just keeps a bag of delegates to create each model type:

public class ModelSelector
{
    private readonly Dictionary<Type, Func<object>> modelLookup = new Dictionary<Type, Func<object>>();

    public void WhenRendering<T>(Func<object> getter)
    {
        modelLookup.Add(typeof(T), getter);
    }

    public object GetModel(Type modelType)
    {
        if (!modelLookup.ContainsKey(modelType))
        {
            throw new KeyNotFoundException(string.Format("A provider for the model type '{0}' was not provided", modelType.FullName));
        }

        return modelLookup[modelType]();
    }
}

Now, the easiest way to implement a view would be:

@model MvcApplication2.ModelSelector
@using MvcApplication2.Models
@{
    var clock = (ClockModel) Model.GetModel(typeof (ClockModel));
}

<h2>The time is: @clock.Now</h2>

You could end here and use this approach.

@model MvcApplication2.Models.NewsModel
<h2>News Widget</h2>
@foreach (var headline in Model.Headlines)
{
    <h3>@headline</h3>
}

When a Razor view is compiled, it inherits a ViewPage<T>, where T is the @model. So we can use reflection to figure out what type the view wanted, and select it.

public class ModelSelectorEnabledRazorViewEngine : RazorViewEngine
{
    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var result = base.CreateView(controllerContext, viewPath, masterPath);

        if (result == null)
            return null;

        return new CustomRazorView((RazorView) result);
    }

    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        var result = base.CreatePartialView(controllerContext, partialPath);

        if (result == null)
            return null;

        return new CustomRazorView((RazorView)result);
    }

    public class CustomRazorView : IView
    {
        private readonly RazorView view;

        public CustomRazorView(RazorView view)
        {
            this.view = view;
        }

        public void Render(ViewContext viewContext, TextWriter writer)
        {
            var modelSelector = viewContext.ViewData.Model as ModelSelector;
            if (modelSelector == null)
            {
                // This is not a widget, so fall back to stock-standard MVC/Razor rendering
                view.Render(viewContext, writer);
                return;
            }

            // We need to work out what @model is on the view, so that we can pass the correct model to it. 
            // We can do this by using reflection over the compiled views, since Razor views implement a 
            // ViewPage<T>, where T is the @model value. 
            var compiledViewType = BuildManager.GetCompiledType(view.ViewPath);
            var baseType = compiledViewType.BaseType;
            if (baseType == null || !baseType.IsGenericType)
            {
                throw new Exception(string.Format("When the view '{0}' was compiled, the resulting type was '{1}', with base type '{2}'. I expected a base type with a single generic argument; I don't know how to handle this type.", view.ViewPath, compiledViewType, baseType));
            }

            // This will be the value of @model
            var modelType = baseType.GetGenericArguments()[0];
            if (modelType == typeof(object))
            {
                // When no @model is set, the result is a ViewPage<object>
                throw new Exception(string.Format("The view '{0}' needs to include the @model directive to specify the model type. Did you forget to include an @model line?", view.ViewPath));                    
            }

            var model = modelSelector.GetModel(modelType);

            // Switch the current model from the ModelSelector to the value of @model
            viewContext.ViewData.Model = model;

            view.Render(viewContext, writer);
        }
    }
}

The view engine is registered by putting this in Global.asax.cs:

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new ModelSelectorEnabledRazorViewEngine());

My home view includes the following lines to test it all out:

@Html.Action("Show", "Widget", new { widgetName = "Clock" })
@Html.Action("Show", "Widget", new { widgetName = "News" })

asp.net mvc - Determine the model of a partial view from the controlle...

asp.net-mvc model-view-controller asp.net-mvc-3
Rectangle 27 21

Prefix it with '/Views' should help.

return View("~/Views/Items/Details.aspx");

I ran into this today, used this suggestion but also needed to add the ".cshtml" extension.

Accessing views with absolute paths on ASP.NET MVC - Stack Overflow

asp.net-mvc views path
Rectangle 27 192

EDIT: Since this has gotten a lot of views, let me start by giving eve...

#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER
#For numbers embedded in sentences, see discussion below

#### NUMBERS AND DECIMALS ONLY ####
#No commas allowed
#Pass: (1000.0), (001), (.001)
#Fail: (1,000.0)
^\d*\.?\d+$

#No commas allowed
#Can't start with "."
#Pass: (0.01)
#Fail: (.01)
^(\d+\.)?\d+$

#### CURRENCY ####
#No commas allowed
#"$" optional
#Can't start with "."
#Either 0 or 2 decimal digits
#Pass: ($1000), (1.00), ($0.11)
#Fail: ($1.0), (1.), ($1.000), ($.11)
^\$?\d+(\.\d{2})?$

#### COMMA-GROUPED ####
#Commas required between powers of 1,000
#Can't start with "."
#Pass: (1,000,000), (0.001)
#Fail: (1000000), (1,00,00,00), (.001)
^\d{1,3}(,\d{3})*(\.\d+)?$

#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$

#Commas optional as long as they're consistent
#Can't start with "."
#Pass: (1,000,000), (1000000)
#Fail: (10000,000), (1,00,00)
^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$

#### LEADING AND TRAILING ZEROES ####
#No commas allowed
#Can't start with "."
#No leading zeroes in integer part
#Pass: (1.00), (0.00)
#Fail: (001)
^([1-9]\d*|0)(\.\d+)?$

#No commas allowed
#Can't start with "."
#No trailing zeroes in decimal part
#Pass: (1), (0.1)
#Fail: (1.00), (0.1000)
^\d+(\.\d*[1-9])?$

Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.

This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111, 9,9,9, or even .,,.. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234and only those numbersout of abc22 1,234.56 9.9.9.9 def 1234 is a wrong answer.

First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.

Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000 format and blocks everything else:

^\d*\.?\d+$
0,000
^\d{1,3}(,\d{3})*(\.\d+)?$

Put them together, and commas become optional as long as they're consistent:

^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$

The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see catch22 and think it's found the number 22. If you're using something with lookbehind support (like .NET), this is pretty easy: replace ^ with (?<!\S) and $ with (?!\S) and you're good to go:

(?<!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S)

If you're working with JavaScript or Ruby or something, things start looking more complex:

(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)

You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).

I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:

  • Decimals starting with the decimal point (e.g. .001 as opposed to 0.001)

Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:

(?<!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S)
(?<!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9.
(?=.)             #The whole thing can't be blank.

(                    #Rules for the integer part:
  0                  #1. The integer part could just be 0...
  |                  #
  [1-9]              #   ...otherwise, it can't have leading zeroes.
  (                  #
    \d*              #2. It could use no commas at all...
    |                #
    \d{0,2}(,\d{3})* #   ...or it could be comma-separated groups of 3 digits each.
  )                  # 
)?                   #3. Or there could be no integer part at all.

(       #Rules for the decimal part:
  \.    #1. It must start with a decimal point...
  \d*   #2. ...followed by a string of numeric digits only.
  [1-9] #3. It can't be just the decimal point, and it can't end in 0.
)?      #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank.
100,000
999.999
90.0009
1,000,023.999
0.111
.111
0
1,1,1.111
000,001.111
999.
0.
111.110000
1.1.1.111
9.909,888

There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.

Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:

(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)

The numbers you're looking for will be in capture group 1.

Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should consider whether you really want to use this in a production environment. Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that might be a number, then another one to weed out whatever isn't a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.

This is a very good attempt, but there may be a problem with it - depending on the greediness of the engine, a given number may partially match two of the competing formats, instrad of singly matching the correct one - i.e. 5000 may yield 500 plus 0 That makes me a little skeptical of trying to cover too much with only a single expression, and that's why i gave a simpler answer with the caveat of possible false positives. At the end of the day, the stringency of the requirements should dictate the solution.

@entonio - That's a fair point. It might work with the latest edit. BTW, your downvote wasn't from me, since you pointed out the potential 1,11,11 match.

I'm using ActionScript, which I believe behaves the same as JavaScript. Using the first pattern you recommended, I get the following results on my test string (For validation, I'm simply returning the matches wrapped in "<<[result]>>"): The<< 5>>000 lb. fox jumped over a<< 9>>9<<,9>><<99>><<.9>><<99>><<98>><<71>>3 foot fence.

Well, one of your up votes is from me :) as I do think your answer is as thorough as it can get and you put work into it. Just to make this a content-comment, a note to the OP, the ?: at the start of groups is there so that they aren't returned autonomously in the result ('captured'), even though they contribute to the matching of the whole expression; each formatted number in the input matches the whole expression.

@Michael and @entonio - See latest edit, which seems to work. This is one of those regex problems that are more difficult than they appear.

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

regex - Regular expression to match numbers with or without commas and...

regex
Rectangle 27 68

To use the custom helper method in your Razor views you will need to bring it into scope. There are two possible ways to do this:

  • Add a @using SomeNamespace in the top of your view with the namespace where the static class containing the helper is defined
  • In ~/Views/web.config, add: <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="SomeNamspace" /> </namespaces> </pages> </system.web.webPages.razor>

Once the custom helper is brought into scope in the view, Intellisense should be able to pick it and you could use it:

Now you helper method needs to do something useful. You could either call existing helpers:

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(this HtmlHelper html)
    {
        return MvcHtmlString.Create("Hello world");
    }
}

If you have a strongly typed view and you wanted to use an expression:

using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(
        this HtmlHelper<MyViewModel> html
    )
    {
        var stateList = new SelectList(new[]
        {
            new { Key = "Alabama", Value = "Alabama" },
            new { Key = "Idaho", Value = "Idaho" },
            new { Key = "California", Value = "California" }
        }, "Key", "Value");
        return Html.DropDownListFor(
            x => x.State, stateList, "-- Select a state --"
        );
    }
}

and then:

@Html.StateDropDownList()

I think you misunderstand. I know how to use the extension method in my view. I just don't know what to do in the extension method to utilize the existing TextBoxFor helper in order to create my own helper, built off the existing helper.

@Chevex, updates are coming, be patient :-)

Bingo, I was missing using System.Web.Mvc.Html and for whatever reason it wouldn't automatically resolve. Thanks!

I get a run-time error in HTML page because it is called with no argument, but the definition includes 1 which is this HtmlHelper helper. Do you know why?

Where do you but your custom Html Helpers in your project ? as asked here ?

c# - Adding your own HtmlHelper in ASP.NET MVC 3 - Stack Overflow

c# asp.net html asp.net-mvc asp.net-mvc-3
Rectangle 27 213

The best way is using ActionFilterAttribute and register your custom class in your global. asax (Application_Start)

public class UserProfilePictureActionFilter : ActionFilterAttribute
{

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.IsAuthenticated = MembershipService.IsAuthenticated;
        filterContext.Controller.ViewBag.IsAdmin = MembershipService.IsAdmin;

        var userProfile = MembershipService.GetCurrentUserProfile();
        if (userProfile != null)
        {
            filterContext.Controller.ViewBag.Avatar = userProfile.Picture;
        }
    }

}

register your custom class in your global. asax (Application_Start)

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        GlobalFilters.Filters.Add(new UserProfilePictureActionFilter(), 0);

    }
@ViewBag.IsAdmin
@ViewBag.IsAuthenticated
@ViewBag.Avatar
[Extension()]
public string MyTest(System.Web.Mvc.HtmlHelper htmlHelper)
{
    return "This is a test";
}

Then you can use it in all views

@Html.MyTest()

I don't understand why this hasn't been upvoted more; it's a much less invasive approach than the others

+1 Nice and clean way to integrate global data. I used this technique to register my site version across all pages.

asp.net mvc - How to set ViewBag properties for all Views without usin...

asp.net-mvc asp.net-mvc-3 autofac viewdata
Rectangle 27 54

for all views (you need dba privileges for this query)

select view_name from dba_views
select view_name from all_views
select view_name from user_views

You mean "We're sorry, the page you requested was not found." ? :)

Display all views on oracle database - Stack Overflow

database oracle view oracle-sqldeveloper
Rectangle 27 52

for all views (you need dba privileges for this query)

select view_name from dba_views
select view_name from all_views
select view_name from user_views

You mean "We're sorry, the page you requested was not found." ? :)

Display all views on oracle database - Stack Overflow

database oracle view oracle-sqldeveloper
Rectangle 27 216

Yes. By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.

return View("~/Views/Wherever/SomeDir/MyView.aspx")

Thanks, this sounds like the solution I should be using. I still wonder if it is possible to display a View from another controller though. I'm guessing this violates some rule in MVC?

In the situation you describe above, yes, you should be using the Shared folder.

Yep, that is also possible. If you do return View("~/Views/Wherever/SomeDir/MyView.aspx") You can return any View you'd like. This doesn't violate any particular rule per se, however, ASP.Net MVC is all about "convention over congfiguration". In other words, the framework is built to operate automatically using certain conventions, and you should utilize it where possible.

Thanks for the explaination. I didn't know Views could be called like that. The Shared directory of course works perfectly :)

new ViewResult { ViewName = "~/Views/Error/Unauthorised.cshtml" };

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

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

Yes. By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.

return View("~/Views/Wherever/SomeDir/MyView.aspx")

Thanks, this sounds like the solution I should be using. I still wonder if it is possible to display a View from another controller though. I'm guessing this violates some rule in MVC?

In the situation you describe above, yes, you should be using the Shared folder.

Yep, that is also possible. If you do return View("~/Views/Wherever/SomeDir/MyView.aspx") You can return any View you'd like. This doesn't violate any particular rule per se, however, ASP.Net MVC is all about "convention over congfiguration". In other words, the framework is built to operate automatically using certain conventions, and you should utilize it where possible.

Thanks for the explaination. I didn't know Views could be called like that. The Shared directory of course works perfectly :)

new ViewResult { ViewName = "~/Views/Error/Unauthorised.cshtml" };

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

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

You can extend Html helper class by this :

using System.Web.Mvc.Html


 public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string name = ExpressionHelper.GetExpressionText(expression);
        object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
        var viewData = new ViewDataDictionary(helper.ViewData)
        {
            TemplateInfo = new System.Web.Mvc.TemplateInfo
            {
                HtmlFieldPrefix = name
            }
        };

        return helper.Partial(partialViewName, model, viewData);

    }

and simply use it in your views like this :

<%= Html.PartialFor(model => model.Child, "_AnotherViewModelControl") %>

This will be incorrect for nested partial rendering. You need to append the new prefix to the old prefix from helper.ViewData.TemplateInfo.HtmlFieldPrefix in the form of {oldprefix}.{newprefix}

@Mahmoud Your code works great, but I was finding that the ViewData/ViewBag was empty when it came time to execute code in the Partial. I found that the helper, of type HtmlHelper<TModel> had a new property ViewData, which hid the base model's. With that, I replaced new ViewDataDictionary(helper.ViewData) with new ViewDataDictionary(((HtmlHelper)helper).ViewData). Do you see any problem with that?

string oldPrefix = helper.ViewData.TemplateInfo.HtmlFieldPrefix; if (oldPrefix != "") name = oldPrefix + "." + name;

ASP.NET MVC partial views: input name prefixes - Stack Overflow

asp.net-mvc spark-view-engine mvccontrib
Rectangle 27 99

You can extend Html helper class by this :

using System.Web.Mvc.Html


 public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string name = ExpressionHelper.GetExpressionText(expression);
        object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
        var viewData = new ViewDataDictionary(helper.ViewData)
        {
            TemplateInfo = new System.Web.Mvc.TemplateInfo
            {
                HtmlFieldPrefix = name
            }
        };

        return helper.Partial(partialViewName, model, viewData);

    }

and simply use it in your views like this :

<%= Html.PartialFor(model => model.Child, "_AnotherViewModelControl") %>

This will be incorrect for nested partial rendering. You need to append the new prefix to the old prefix from helper.ViewData.TemplateInfo.HtmlFieldPrefix in the form of {oldprefix}.{newprefix}

@Mahmoud Your code works great, but I was finding that the ViewData/ViewBag was empty when it came time to execute code in the Partial. I found that the helper, of type HtmlHelper<TModel> had a new property ViewData, which hid the base model's. With that, I replaced new ViewDataDictionary(helper.ViewData) with new ViewDataDictionary(((HtmlHelper)helper).ViewData). Do you see any problem with that?

string oldPrefix = helper.ViewData.TemplateInfo.HtmlFieldPrefix; if (oldPrefix != "") name = oldPrefix + "." + name;

ASP.NET MVC partial views: input name prefixes - Stack Overflow

asp.net-mvc spark-view-engine mvccontrib
Rectangle 27 11

Make sure you have your views.

app/views/[class_name]/[method_name]
app/views/notifier/send_message.html.erb

Actually you can name the view as send_message.text.erb to make it more clear.

Why have two separate files that do the same thing?

ruby on rails 3 - Invalid filename in email (ActionMailer) - Stack Ove...

ruby-on-rails-3 actionmailer
Rectangle 27 507

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}
LayoutInjecterAttribute
ActionFilters

@VeeKeyBee, your question is about Entity Framework - a technology I am not interested in.

One potential problem with LayoutInjecterAttribute: It is called before the controller's OnException method. So, if the controller provides a view result during exception handling, the layout won't be set.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStar...

asp.net-mvc layout asp.net-mvc-3 razor
Rectangle 27 504

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Perfect answer thanks! Out of curiosity Scott Gu says you can set it an action filter. You wouldn't happen to have an example of that too would you? Answer will be accepted as soon as SO allows.

LayoutInjecterAttribute

thank you! Thats a very complete awesome answer! I was looking for a Layout property not MasterName no wonder I couldn't find it:)

ActionFilters

@VeeKeyBee, your question is about Entity Framework - a technology I am not interested in.

One potential problem with LayoutInjecterAttribute: It is called before the controller's OnException method. So, if the controller provides a view result during exception handling, the layout won't be set.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStar...

asp.net-mvc layout asp.net-mvc-3 razor
Rectangle 27 538

Let's say you generate a bunch of views that are similar. You could set an OnClickListener for each view individually:

button1.setOnClickListener(new OnClickListener ... );
button2.setOnClickListener(new OnClickListener ... );
 ...

Then you have to create a unique onClick method for each view even if they do the similar things, like:

public void onClick(View v) {
    doAction(1); // 1 for button1, 2 for button2, etc.
}

This is because onClick has only one parameter, a View, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.

getTag
setTag
button1.setTag(1);
button2.setTag(2);

Now we can use the same OnClickListener for every button:

listener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        doAction(v.getTag());
    }
};

It's basically a way for views to have memories.

@Matthew Willis but we can do that using the view.getId() too. is not it ?

@AndroidKiller you could, but with setTag() you can put any object you want, even custom classes - so you can use them to persist a reference to the data that the view is displaying

What should i do if i only want to change the background color of the button that is clicked ??? I am getting the position by getTag().

public void ui_click(View view){ if(20==((int)view.getTag())) view.setBackgroundColor(colorInt); }
onEditorActionListener
EditText

android - What is the main purpose of setTag() getTag() methods of Vie...

android view
Rectangle 27 37

iOS 7 apparently supports the Status Bar being hidden for some views but not others. To hide it for all views, do the following:

  • Make sure Hide during application launch is still checked, to support previous OS versions.
View controller-based status bar appearance
NO

This worked for me except that the status bar reappears after showing a UIImagePicker.

This appears to fully hide the status bar which I don't want to do. Ideally, I would just like to shift down my content so the status bar doesn't hover over it and overlap my app header. FYI I'm making a phonegap/cordova app.

Point 2) alone allowed me to hide the status bar on iOS7 and move my view 'back down the screen' and now it's all as I want it. Thanks a lot. (I have no Nav bar, just the status bar)

iphone - Status bar appear over my view's bounds in iOS 7 - Stack Over...

iphone ios6 ios7 xcode5
Rectangle 27 37

iOS 7 apparently supports the Status Bar being hidden for some views but not others. To hide it for all views, do the following:

  • Make sure Hide during application launch is still checked, to support previous OS versions.
View controller-based status bar appearance
NO

This worked for me except that the status bar reappears after showing a UIImagePicker.

This appears to fully hide the status bar which I don't want to do. Ideally, I would just like to shift down my content so the status bar doesn't hover over it and overlap my app header. FYI I'm making a phonegap/cordova app.

Point 2) alone allowed me to hide the status bar on iOS7 and move my view 'back down the screen' and now it's all as I want it. Thanks a lot. (I have no Nav bar, just the status bar)

iphone - Status bar appear over my view's bounds in iOS 7 - Stack Over...

iphone ios6 ios7 xcode5
Rectangle 27 37

iOS 7 apparently supports the Status Bar being hidden for some views but not others. To hide it for all views, do the following:

  • Make sure Hide during application launch is still checked, to support previous OS versions.
View controller-based status bar appearance
NO

This worked for me except that the status bar reappears after showing a UIImagePicker.

This appears to fully hide the status bar which I don't want to do. Ideally, I would just like to shift down my content so the status bar doesn't hover over it and overlap my app header. FYI I'm making a phonegap/cordova app.

Point 2) alone allowed me to hide the status bar on iOS7 and move my view 'back down the screen' and now it's all as I want it. Thanks a lot. (I have no Nav bar, just the status bar)

iphone - Status bar appear over my view's bounds in iOS 7 - Stack Over...

iphone ios6 ios7 xcode5
Rectangle 27 27

Add your namespace to the views web.config under the namespaces element:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="MyProject.WebUI.Properties" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Note that you might have to close and reopen the view file that you want intellisense in for these changes to take affect.

@napspinksi make sure the web.config you are updating is the one in Views folder

Thanks! Any idea how to get it included in intellisense?

@amurra (and naspinki) I had to close the view file and then re-open it for intellisense to pick up the new namespace. (Visual Studio 2010)

How do you implement a @using across all Views in Asp.Net MVC 3? - Sta...

asp.net-mvc asp.net-mvc-3 razor namespaces