Here we will take a TextBox control and a submit button in view. On click of submit button we will capture the model class property value at controller end and read the text file append the user added value to the already added text.
public class FileModel
{
public string FileContent { get; set; }
}
In above code i have defined a model class property named as FileContent of string type. After this i have added a new controller class file. Now create a HttpGet method of IActionResult method in controller. [HttpGet]
public IActionResult Index()
{
FileModel fileModel = new FileModel();
return View(fileModel);
}
In above method I have created the object of the model class and pass it in view. After this we will create a view.@model FileModel
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
<div style="color:red">@ViewBag.Message </div>
<div style="font-weight:bold;">Enter Text:</div>
<div>
@Html.TextAreaFor(m => m.FileContent, new { @class = "form-control" })
</div>
<br />
<div><input type="submit" value="Submit" /></div>
}
In above code I have added the reference of the model class file. After this I have added the form tag by using Html.BeginForm. In this form tag I have added the controller and action name. To add a textarea by using Html.TextAreaFor to provide the input control. Now input of submit button to post the form. Now add a HttpPost method and add the below code.[HttpPost]
public IActionResult Index(FileModel fileModel)
{
try
{
string parentPath = @"wwwroot\Demofiles\";
string texttfilename = "demotextfile.txt";
string textfilepath = Path.Combine(Directory.GetCurrentDirectory(), parentPath, texttfilename);
System.IO.File.AppendAllText(textfilepath, fileModel.FileContent + Environment.NewLine);
ViewBag.Message = "Text data append completed successfully.";
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return View();
}
In above code I have passed the model class as parameter to the IActionResult method. This will help us to capture the user added value in view at controller end. After that I have declared the path for the folder and in next variable, I have added the text file name where we will append the user added value. Here Path.Combine(Directory.GetCurrentDirectory(), path, filename); to concomitant the path of the file. System.IO.File.AppendAllText(path,texttoappend) for appending the user added to the existing text file in wwwroot folder. Now let's run the code to check the output.Now click on Submit button we will hit the break point and here at controller end we will get the user entered value in model class property.
Now press F5 to complete the code execution.
Let's check the text file content.