Working code. Fully tested
in you _Layout.cshtml
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
in your About.cshtml
Table mark up
<table style="background-color: lightgreen; border: solid 2px black;">
<tr>
<td>
<b>Name</b>
</td>
<td>
<b>Size</b>
</td>
<td>
<b>Preview</b>
</td>
<td>
<b>Read File</b>
</td>
</tr>
@foreach (var file in Model)
{
<tr>
<td>
@file.Name
</td>
<td>
@(file.Size / 1000) KB
</td>
<td>
@(file.extension)
</td>
<td>
<input id="btnreadfile" name="@file.Name" class='btnClick' type="button" value="Read File"/>
<textarea rows="4" cols="50">
</textarea>
</td>
</tr>
}
</table>
in your About.cshtml all the way bottom add this script
<script>
$.ajax({
url: "/Home/ReadTextFile",
type: "GET",
data: { fileName: $(this).attr("name") },
DataType: "text",
success: function (str) {
alert(str);
$("textarea").val(str); // this line has to be replaced with more dynamic jQuery selector that can select this button next textarea
//$(this).next("textarea").val(str);
},
error: function (err) {
alert(err);
}
});
});
</script>
in Your Controller
- Add reference
using System.Runtime.InteropServices.ComTypes;
- add a JsonResult Method
public JsonResult ReadTextFile(string fileName)
{
string retString = string.Empty;
string path = Path.Combine(Server.MapPath("~/uploads") , fileName );
if (System.IO.File.Exists(path))
{
if (Path.GetExtension(path) == "doc" || Path.GetExtension(path) == ".docx")
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object readOnly = true;
object wordPath = path;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(
ref wordPath,
ref miss,
ref readOnly,
ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss);
for (int i = 0; i < docs.Paragraphs.Count; i++)
{
retString += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
}
}
else if (Path.GetExtension(path) == "txt")
{
using (StreamReader sr = new StreamReader(path))
{
retString = sr.ReadToEnd();
}
}
}
return Json(retString, JsonRequestBehavior.AllowGet);
}
Note: I have considered to read only files with extension .doc, .docx and .txt
any other extensions should be handled further