在 CSHTML (Razor) 上命名文本文件
我有一个带有用于标题输入和正文输入的文本区域的页面。
保存包含这些内容的文本文件很容易,问题是,如何使文件以标题输入中放置的内容命名?
我尝试了这个:(
@{
var result = "";
if (IsPost)
{
var title = Request["title"];
var body = Request["body"];
var filedata = title + "," + body + Environment.NewLine;
var dataFile = Server.MapPath("/App_Data/Request["title"]");
File.WriteAllText(@dataFile, filedata);
result = "Information saved.";
}
}
请注意, var title = Request["title"];
表示它从名为“title”的文本输入请求)。我想要得到的是输入也将是其保存的文件的名称。
但似乎这个领域:
var dataFile = Server.MapPath("/App_Data/Request["title"]");
不是正确的方式。
正确的做法是什么?
I have a page with a text area for title input and body input.
Saving a text file with those things is easy, the question is, how can I make the file to be named after whatever was placed in the title input?
I tried this:
@{
var result = "";
if (IsPost)
{
var title = Request["title"];
var body = Request["body"];
var filedata = title + "," + body + Environment.NewLine;
var dataFile = Server.MapPath("/App_Data/Request["title"]");
File.WriteAllText(@dataFile, filedata);
result = "Information saved.";
}
}
(Note that var title = Request["title"];
means that its requesting from a text input named "title"). What I want to get is that the input will also be the name of the file its saving.
But it seems that this area:
var dataFile = Server.MapPath("/App_Data/Request["title"]");
is not the correct way.
What is the correct way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几个指针;首先,这种逻辑应该在控制器中,而不是在视图中。您的视图应该显示有关您的模型的信息,您的控制器执行操作。
其次,以下应该可以解决问题(在控制器中!):
值得注意的是:
Server.MapPath("~/TextFiles")
为您提供了Web应用程序根目录中TextFiles目录的路径文件的存储位置。SaveSuccessful
的操作。当然,您需要错误处理和其中的各种其他内容,但希望这会有所帮助。
Couple of pointers; firstly this sort of logic should be in a Controller, not in a View. Your Views are supposed to display information about your model, your Controllers carry out operations.
Secondly, the following should do the trick (in a Controller!):
Of note:
Server.MapPath("~/TextFiles")
gives you the path to a TextFiles directory in the root of your web application where the files will be stored.SaveSuccessful
on the same ControllerOf course you need error handling and all sorts of other things in there, but hopefully that helps.