在使用 razor(C#) 和 html 从 POST 请求请求数据后,如何在 <p> 元素中显示变量

How do i display a variable in a <p> element after requesting the data from a POST request using razor(C#) and html

我注意到如果我不使用 Request["name"]; 这会起作用,但显然我需要从我的表单中获取信息。我想在确认消息中显示 'name'。我正在使用 visual studio asp.net 空 webapp

这是剃须刀代码

 @{
    string title = "This is the title";

    string name = "";
    if (IsPost)
    {

        name = Request["name"];
        string email = Request["email"];
        string message = Request["message"];
    }
}


<p>@name</p>

如果我应该包括任何其他代码,请告诉我,但我认为这就是您需要看到的全部内容。

控制器:

public ActionResult Test()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Test(string Name, string Message, string email)
    {
        ViewBag.Name = Name;
        ViewBag.Message = Message;
        ViewBag.email = email;
        return View();
    }

Razor 视图:

 @using (Html.BeginForm())
{
    <input type="text" name="Name" />
    <input type="text" name="Message" />
    <input type="email" name="email" />
    <input type="submit" value="submit" />
}

<p>@ViewBag.Name</p><br>
<p>@ViewBag.Message</p><br>
<p>@ViewBag.email<p>

我找到了一个比其他答案更简单的解决方案。

@{
    string title = "This is the title";

    var names = "";
    var emails = "";

    if (IsPost)
    {
        var name = Request["name"];
        var email = Request["email"];
        string message = Request["message"];

        names = name;
        emails = email;
    }
}

通过将 Request["name"]; 重新初始化为另一个变量,它允许我在我的 html 中使用 names 变量或 emails 变量。这使得MVC的使用变得多余并且更加简单。

<p>Name: @names</p>