3

How can I convert the below code to a controller in MVC.

I want to write inside the text file in MVC. I have tried to use this way that is shown below. So now I just want to convert this code to a controller. How can I do that?

My current code look like this below and it working

@{
    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>

I just want to convert this part to a CONTROLLER

@{
    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.";
    }
}
Dlamini.M
  • 109
  • 1
  • 10

1 Answers1

1

this is your modal

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

these are your actionresults

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