如何将以下代码转换为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>
我只想将此部分转换为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.";
}
}
答案 0 :(得分:1)
这是您的模式
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();
}