如何在視圖中呼叫控制器 GET 方法?(.NET 6.0)
如何在單擊后顯示結果,例如,在按鈕上?
控制器方法:
public string GetString()
{
string time = "Operation time: " _lastExecutionTime;
return time;
}
uj5u.com熱心網友回復:
我認為您真正想要實作的是讓您的操作方法在視圖上作業。無需將其寫入控制器。你需要在你的視圖上做這樣的事情。
@functions{
public string GetString()
{
string time = "Operation time: " _lastExecutionTime;
return time;
}
}
然后你會像這樣在你的 HTML(DOM) 塊中呼叫它
<div>
<table>
<tr> <td> @GetString() </td></tr>
</table>
</div>
所有這些都在視圖上。
但是如果你必須在Controller中呼叫Action Method,你需要Action Method回傳一個ActionResult——可能是View或者Redirect。但不回傳文字值。
您可以通過 View 上的以下代碼執行此操作
<form method="post" action="/Process/myData">
<input type="text" name="fullname">
<input type="submit">
</form>
然后在您的流程控制器中,您的操作方法將像
public ActionResult myData(){
...do something...
return View();
}
您也可以通過將表單方法更改為 GET 來呼叫 Get Action 方法。您需要知道 GET 主要在進行搜索時使用。
大多數時候您將呼叫動作方法,您還需要知道控制器中的動作方法將包含引數,這些引數將是物體模型的物件。那是當您使用強型別視圖時。
上面的 HTML 代碼可以像這樣用 C# 撰寫
@using (Html.BeginForm("myData", "Process", FormMethod.Post, new { @class = "user", role = "form" })){
@Html.Editor("fullname", new { htmlAttributes = new { @class = "form-control form-control-user", @required = "required", @Placeholder="fullname" } })
<input type="submit"/>
}
或者
@using (Html.BeginForm()){
@Html.Editor("fullname", new { htmlAttributes = new { @class = "form-control form-control-user", @required = "required", @Placeholder="fullname" } })
<input type="submit"/>}
如果您在行程控制器中 myData 操作方法的視圖中。
uj5u.com熱心網友回復:
或者您可以使用 ajax 呼叫后端 API:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
public string GetString()
{
string time = "Operation time: " DateTime.Now;
return time;
}
}
<input type="button" id="btnGet" />
<div id="value"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "Get",
url: "api/Values",
success: function (response) {
alert(response);
$("#value").html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
結果:單擊按鈕

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411791.html
標籤:
上一篇:System.InvalidOperationException:'已經有一個打開的DataReader與此Connection關聯,必須先關閉
