Click here to Skip to main content
15,880,503 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi guys,
I have got a button that is created I created using HMTL. I want when this button is clicked to call a message that i have coded using c#.

My c# function generates random numbers, and I want this button in HTML when clicked to display the generated number.

C# Code:

C#
public class HomeController : Controller
   {
     private  static Random rand = new Random();
     private string _randomnumber;



       public ActionResult Index()
       {

           for (int i = 0; i < 2; i++)
           {
             _randomnumber= (Convert.ToString(rand.Next(1000, 9900)));
              return new JsonResult { Data = _randomnumber, JsonRequestBehavior = JsonRequestBehavior.AllowGet };


           }

           return View();

       }


HTML Code:

XML
<input type ="button" onclick=" GetMessage() " value=" Get Message"/>
        <p></p>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            function GetMessage() {

                $.get("/{HomeControlle}r/{Index}", function(data) {
                    $("p").html(data);
                });
            }


        </script>



When I run this application, the button does not show, the browser only shows the generated number. Can someone please help?
Posted

1 solution

try this

C#
public class HomeController : Controller
   {
     private  static Random rand = new Random();
     private string _randomnumber;



       public ActionResult Index()
       {
           return View();

       }

C#
public int Random()
{
for (int i = 0; i < 2; i++)
           {
             _randomnumber= (Convert.ToString(rand.Next(1000, 9900)));
              return new JsonResult { Data = _randomnumber, JsonRequestBehavior = JsonRequestBehavior.AllowGet };


           }
return _randomnumber;
}



XML
<input type ="button" onclick=" GetMessage() " value=" Get Message"/>
        <p></p>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            function GetMessage() {

                $.get("/{HomeControlle}r/{Random}", function(data) {
                    $("p").html(data);
                });
            }


        </script>
 
Share this answer
 
Comments
1Future 24-Jul-14 9:33am    
hi, than you very replysoneing , do u know how convert JsonReult to int???

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900