![](/img/trans.png)
[英]How to do you make both a Razor Page and C# code framework with ASP.NET Core?
[英]How do you pass post form variables in ASP.NET C#/Razor?
我是C#/ Razor的新手,並且不知道如何使用post方法傳遞表單數據。 這是我嘗試過的:
在login.cshtml中:
string username = Request.Form["username"];
string password = Request.Form["password"];
和
string username = Request.Form.Get("username");
string password = Request.Form.Get("password");
在_AppStart.cshtml中,我嘗試過:
AppState["username"] = HttpContext.Current.Request.Form["username"];
AppState["password"] = HttpContext.Current.Request.Form["password"];
一切都不返回。
這是login.cshtml中的表單元素:
<form action="index.cshtml" method="post" data-ajax="false">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
如果需要在MVC控制器和View之間傳遞數據,則必須讓Asp知道控制器要調用哪個動作。
為此,您可以在razor中使用諸如BeginForms之類的東西,指定所需的信息。
看起來像這樣:
@Html.BeginForm("YourAction", "YourController", FormMethod.Post){
@Html.TextBoxFor(employee => employee.FirstName);
@Html.TextBoxFor(employee => employee.LastName);
@Html.TextBoxFor(employee => employee.Age);
<input type="submit" value="Edit" />
}
在此代碼段之后,您會看到您需要一個Controller並根據此處提供的名稱命名一個ActionResult,此外,您可以指定是僅在發布時還是僅在獲取表單時才執行該操作
一個可能的例子可能是如下代碼所示的編輯
[HttpPost]
public ActionResult YourAction(Employee emp)
{
if (ModelState.IsValid)
{
// do smth.
}
return View("Name Of the view");
}
請注意,您需要在Controller中進行定義,並且HttpPost屬性使Asp知道這是僅發布的ActionResult。 這意味着只有發布請求可以使用此方法。 此外
如果您希望此ActionResult的獲取和發布請求均可用,則只需刪除該屬性,然后默認情況下,該屬性將在獲取和設置請求中可用。
您可以查看此論壇條目
在輸入類型“提交添加formaction =“ ActionMethodName”
@using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="postedFile"/>
<input type="submit" **formaction="UploadData"** value="UploadData"/>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.