如何将以下代码转换为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.";
    }
}

最佳答案

这是你的模态

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();
}

关于c# - 如何在MVC中写入文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34942020/

10-11 10:55