如何在ASP.Net MVC中通过HTML调用C#函数 [英] How do I call a C# Function by HTML in ASP.Net MVC
问题描述
大家好,
我有一个使用HMTL创建的按钮。我想要点击这个按钮来调用我用c#编码的消息。
我的c#函数生成随机数,点击时我想要HTML中的这个按钮显示生成的数字。
C#代码:
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:
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代码:
HTML Code:
<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?
推荐答案
.get(/ {HomeControlle} r / {Index},function(data){
.get("/{HomeControlle}r/{Index}", function(data) {
(p)。html(data);
});
}
< / script < span class =code-keyword>>
("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?
试试这个
try this
public class HomeController : Controller
{
private static Random rand = new Random();
private string _randomnumber;
public ActionResult Index()
{
return View();
}
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;
}
<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() {
这篇关于如何在ASP.Net MVC中通过HTML调用C#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!