Pages

Friday, 18 December 2015

Calling a client side script form server side (from Controller's action) in asp.net MVC

Problem 9:

 In my asp.net MVC website I have been in a situation where I have multiple forms on my page and some other content as well.
I need to move to the top of the page on successful submission. But obviously successful submission is determined on some Controller's action.

Solution 9:

So for that purpose I have written following code in my controller's action.
-Generate the string for script to scroll to top(Any script can be added here)
-Setting this script to a ViewBag variable.


[HttpPost]
public ActionResult JoinOurSite(Member member)
{
  StringBuilder strScript = new StringBuilder();
  strScript.Append("<script type=\"text/javascript\">");
  strScript.Append("$('html, body').animate({ scrollTop: 0 }, 800);");
  strScript.Append("</script>"
);
   
   bool isSubmitted= true;
    //You may write some submission logic here


       if(isSubmitted)
         {
          ViewBag.ScollToTop =strScript;
         } 

    

}

And then I just simply call this ViewBag variable on my view. as shown


  @Html.Raw(ViewBag.ScollToTop)  
 

And that did the trick for me.

want to achieve this functionality in simple asp.net

No comments:

Post a Comment