用web中c#实现用类、异常处理和方法实现两个数的商,通过按钮“=”执行技术结果<br/>
时间: 2024-09-23 12:03:24 浏览: 86
在Web应用中,使用C#来实现计算两个数的商通常会涉及到前端HTML页面的交互和后端C#代码的处理。首先,你需要创建一个简单的HTML页面,包含两个输入框用于用户输入数字,一个按钮用于触发计算,以及一个地方显示结果。后端则用ASP.NET MVC或类似框架编写C#服务。
1. **HTML部分**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Divide Two Numbers</title>
</head>
<body>
<form id="calculatorForm">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1"><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2"><br>
<button type="submit" value="Calculate">=</button>
<div id="result"></div>
</form>
<script src="~/scripts/calculator.js"></script>
</body>
</html>
```
2. **C#后端部分 (Controller)**:
```csharp
using System;
using Microsoft.AspNetCore.Mvc;
public class CalculatorController : Controller
{
[HttpPost]
public JsonResult DivideNumbers(int num1, int num2)
{
if (num2 == 0) // 异常处理,防止除零错误
return Json(new { error = "Cannot divide by zero." });
int result = num1 / num2;
return Json(new { result });
}
}
```
3. **JavaScript (Calculator.js)**:
```javascript
document.getElementById('calculatorForm').addEventListener('submit', function(e) {
e.preventDefault();
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
$.ajax({
url: "@Url.Action("DivideNumbers", "Calculator")",
method: 'POST',
data: { num1: num1, num2: num2 },
success: function(response) {
document.getElementById('result').innerText = response.result;
},
error: function(xhr, status, error) {
console.error(error);
document.getElementById('result').innerText = xhr.responseText;
}
});
});
```
阅读全文