benone
benone

Reputation: 686

About ASP.NET Web Pages Global

I am new learner to asp.net. I saw “_appstart.cshtml”, “_pagestart.cshtml” and “_viewstart.cshtml” which act like global headers or footer.

(1)If I want to trigger something right before the page is output, should I put the code in _viewstart.cshtml of others?

(2)Let C be the html code just before output, beside appending code to C can I replace code from C? Such as making all text uppercase or replace some text?

(3)Will asp.net cache this process so that I won't run each time?

Upvotes: 0

Views: 112

Answers (1)

user2377970
user2377970

Reputation:

benone

Answer to Point 1

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default

Actually it's like a BasePage in ASP.Net where we can keep the common code.

Or you can write the logic directly in the View like below.

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
  if (Some Consition) {
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
  }
}

Alternatively

You can override the Action Executing method, which executes before executing the Action Method. You can set it for a particular Action method or for the Complete Controller

Below is the code for setting it for Complete Controller.

protected override void OnActionExecuting(ActionExecutingContext ctx) {
    base.OnActionExecuting(ctx);
}

Below is the Code for Setting it for Particular Action method

[MyAttribute(SomeProperty = "")]
public ActionResult Index()
{
     return View("Index");
}

public class MyAttribute : ActionFilterAttribute
{
    public string SomeProperty { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
    }
}

Answer to Point 2

You can use

  var str = Html.Partial("_Partial_View_Name");

Partial returns an MvcHtmlString. You can intercept the output by setting it to a variable and make the necessary change.

Answer to Point 3

Yes. Below is the sample code

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        [OutputCache(Duration=10, VaryByParam="none")]
        public ActionResult Index()
        {
            return View();
        }

    }
}

The output of the Index() action is cached for 10 seconds

Upvotes: 2

Related Questions