开发者

Access Div Id placed in _Layout MVC3

开发者 https://www.devze.com 2023-02-18 13:01 出处:网络
I am working in MVC3. I have created a DIV in _Layout.cshtml filefor showing Error Messages and i have created a C# class ErrorMessag开发者_JS百科e in Views Folder.

I am working in MVC3. I have created a DIV in _Layout.cshtml file for showing Error Messages and i have created a C# class ErrorMessag开发者_JS百科e in Views Folder.

DIV in _layout.cshtml file:

This is class ErrorMessage code:

  public static class ErrorMessage
    {
        public static void Show(string message)
        {
            ErrorMessageDiv.InnerText = message;
        }
        public static void Hide()
        {
        }
    }

In the class ErrorMessage it gives error

"ErrorMessageDiv does not exist in current context"

Any idea how to do it in MVC3?


How about creating a section of code in _layout.cshtml that looks for an error message in the TempData collection using a specific key.

Then in your controller, if an error has occurred, add the error text to the TempData and it will be rendered.

Here is an example:

In your controller, check for some error and add to the TempData:

public ActionResult Index()
    {
        bool isError = true;

        if (isError)
        {
            TempData["ErrorMessage"] = "There has been an error";
            // Or if you want to use the ErrorMessage class
            // ErrorMessage.ShowError("There has been an error");
        }
        return View();
    }

Then in your master _layout.cshtml template

<body>

@if (TempData["ErrorMessage"] != null)
{
    <div class="Error">
        @TempData["ErrorMessage"]
    </div>
}

@RenderBody()

The TempData will remove the value from itself after it has been accessed once.

If you still wish to use the ErrorMessage class then change to wrap the TempData.

public static class ErrorMessage
{
   public static void ShowError(string message)
   { 
      TempData["ErrorMessage"] = message;
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消