1

can we print error message before form start, I am using mvc v4

this is my controller action code [HttpGet]

        public ActionResult ChangePassword(string aToken)
        {
          aToken = Server.UrlDecode(aToken);

          if (aToken != null)
          {
           .........
           }
          else
          {
      ViewBag.Error = "Sorry, this link is not being recognized as valid. 
          }

    return view();`enter code here`
        }

this is my cshtml file

    @if (ViewBag.Error != null)

    {
      <p class="text-danger">
        @ViewBag.Error
      </p>
    }
    else
    {
      using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { 
     @class = "form-horizontal ", role = "form" }))
      {

         ........................
      }

    }`enter code here`

technicality, is this correct?

2 Answers2

0

Is this solves the problem? Yes. However, it would be more secure just to Redirect user to another page with static text instead. Also, you can use ModelState but it will create problems on post actions.

Ssheverdin
  • 111
  • 5
0

Hi we can print error message anywhere we want , according to the place we are providing the error message, it will render the page.

So as per your above code itself , viewbag will print the error message before the form begin, but one small clarification.

ViewData and TempData require typecasting and null checking whereas ViewBag doesn't need such checking.

It will save you few lines of code as below:

 <p class="text-danger">
    @ViewBag.Error
  </p>
  using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { 
 @class = "form-horizontal ", role = "form" }))
  {

     ........................
  }

Additional info:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

Hope above information was helpful

Thanks

Karthik

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12
  • we can put it anywhere, but does it possible to get it in another partialcontrol? – Anirudha Gupta Jun 09 '17 at 01:29
  • Hi Anirudha Gupta , i hope here partialcontrol control means partial view if so yes , We can pass and get it as a model itself. kindly refer this link : https://stackoverflow.com/a/20368646/3397630 . thanks – Karthik Elumalai Jun 09 '17 at 01:36