如何使用 MonoDevelop在 C# 中检索 HTML 文本框的值
本文关键字:文本 HTML 检索 何使用 MonoDevelop | 更新日期: 2023-09-27 18:35:52
我是MonoDevelop,C#和Linux的新手。为了了解事情是如何工作的,我正在尝试制作一个简单的网页来输入矩形的高度和宽度,然后使用提交按钮来计算和显示面积。
我有两个问题。首先,我无法让提交按钮实际执行任何操作。其次,我在获取 C# 代码中的文本框值时遇到问题。一旦我得到它,我想我可以处理这些值来计算面积并将其吐出。我相信Request.Form命令是我的问题点。
这是我到目前为止所拥有的:
<body>
<div>
Height <input type="text" name="inHeight" value=1 /><br />
Width <input type="text" name="inWidth" value=1 /><br />
<br />
<input type="button" name="btnCalculateArea" value="Calculate Area" onclick="CalculateArea()" /><br />
<br />
<%= Html.Encode(ViewData["Message"]) %>
</div>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace rectangle_area.Controllers
{
public class HomeController : Controller
{
public string strHeight;
public string strWidth;
public int intHeight;
public int intWidth;
public double dblArea;
public ActionResult Index ()
{
return View ();
}
public ViewResult CalculateArea ()
{
strHeight = Request.Form ["inHeight"];
strWidth = Request.Form ["inWidth"];
if (strHeight != null && strWidth != null) {
intHeight = Convert.ToInt16 (strHeight);
intWidth = Convert.ToInt16 (strWidth);
dblArea = intHeight * intWidth;
ViewData ["Message"] = "The area of this rectangle is " + dblArea + " square units.";
} else {
ViewData ["Message"] = "Please enter values for the Height and Width.";
}
return View ();
}
}
}
您必须在那里绑定一个对控制器进行 ajax 调用的函数。
谢谢你的指示,克里斯托斯!在朋友和更多研究的帮助下,我让它工作了。这是我最终得到的:
<head runat="server">
<title>Calculate the area of a rectangle</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/Home/CalculateArea';
$('#calcBtn').click(function(){
$.ajax({
type: "GET",
url: serviceURL,
data: { inHeight: $("#inHeight").val(), inWidth: $("#inWidth").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
<body>
<div>
Height <input type="text" id="inHeight" value=2 /><br />
Width <input type="text" id="inWidth" value=3 /><br />
<br />
<input id="calcBtn" type="submit" value="Calculate Area" /><br />
<br />
</div>
</body>
[HttpGet] 公共操作结果计算面积 () { strHeight = Request.Params ["inHeight"]; strWidth = Request.Params ["inWidth"]; if (strHeight != null && strWidth != null) { intHeight = Convert.ToInt16 (strHeight); intWidth = Convert.ToInt16 (strWidth); dblArea = intHeight * intWidth; 视图数据 ["消息"] = "此矩形的面积为 " + dblArea + " 平方单位。 } else { 查看数据 ["消息"] = "请输入 0 到 999 之间的值。 } 返回 Json(ViewData["Message"], JsonRequestBehavior.AllowGet); }