如何在 MVC 中写入文本文件

本文关键字:文本 文件 MVC | 更新日期: 2023-09-27 18:31:22

如何将以下代码转换为MVC中的控制器。

我想在MVC的文本文件中写入。我尝试使用如下所示的这种方式。所以现在我只想将此代码转换为控制器。我该怎么做?

我当前的代码如下所示,并且可以正常工作

@{
    var result = "";
    if (IsPost)
    {
        var firstName = Request["FirstName"];
        var lastName = Request["LastName"];
        var email = Request["Email"];
        var userData = firstName + "," + lastName +
            "," + email + Environment.NewLine;
        var dataFile = Server.MapPath("~/App_Data/data.txt");
        File.AppendAllText(@dataFile, userData);
        result = "Information saved.";
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Write Data to a File</title>
</head>
<body>
    <h5>Write in a text file</h5>
    <form id="form1" method="post">
        <div>
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input id="FirstName" name="FirstName" type="text" /></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input id="LastName" name="LastName" type="text" /></td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input id="Email" name="Email" type="text" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit" /></td>
                </tr>
            </table>
        </div>
        <div>
            @if (result != "")
            {
                <p>Result: @result</p>
            }
        </div>
    </form>
</body>
</html>

我只想将此部分转换为控制器

@{
    var result = "";
    if (IsPost)
    {
        var firstName = Request["FirstName"];
        var lastName = Request["LastName"];
        var email = Request["Email"];
        var userData = firstName + "," + lastName +
            "," + email + Environment.NewLine;
        var dataFile = Server.MapPath("~/App_Data/data.txt");
        File.AppendAllText(@dataFile, userData);
        result = "Information saved.";
    }
}

如何在 MVC 中写入文本文件

这是你的模态

public class yourFormModal
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

这些是你的行动结果

public ActionResult yourPage()
{
    return View();
}
[HttpPost]
public ActionResult yourPage(yourFormModal yfm)
{
    var firstName = yfm.FirstName;
    var lastName = yfm.LastName;
    var email = yfm.Email;
    //do whatever you want...
    return View();
}