当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Why is my FileSystemWatcher flag not updating in my razor view

问题描述:

I have this MVC 5 project set up to run with IIS Express on VS2015. It makes use of the FileSystemWatcher to monitor a folder and populate a list accordingly. Every 5 seconds I check the state of the FolderChanged flag. When it is true I want to alert the user and reset the flag to false. I have verified that the FileSystemWatcher works and the folder is being correctly monitored. But the problem is that the FolderChanged flag is never seen to be true in the razor view but it does get updated in the Do_Something method. I fear that I may be missing something fundamentally simple but i have no idea what. Any help will be appreciated.

model class:

public class LogFileParser

{

public List<string> FolderRecords { get; set; }

public bool FolderChanged { get; set; }

private FileSystemWatcher Folder_Watcher;

public LogFileParser()

{

//set up list folder path and filesystemwatcher

Folder_Watcher.Changed += Do_Something();

Folder_Watcher.EnableRaisingEvents = true;

}

private void Do_Something(object sender, FileSystemEventArgs e)

{

//populate FolderRecords list

FolderChanged = true;

}

}

controller class:

public class DemoController : Controller

{

public ActionResult Test()

{

LogFileParser log_file_parser = new LogFileParser();

return View(log_file_parser);

}

[HttpPost]

public ActionResult Test(LogFileParser log_file_parser)

{

return View(log_file_parser);

}

}

razor view:

@model MonitoringMachineParams.Models.LogFileParser

@{

ViewBag.Title = "Test";

Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>Test</h2>

<script type="text/javascript">

$(document).ready(function () {

window.setInterval(function () { Update(); }, 5000);

});

function Update() {

@if (Model.FolderChanged){

Model.FolderChanged = false;

Html.HiddenFor(m => m.FolderChanged);

<text>alert("hello");</text>

}}

</script>

网友答案:

I think you don't understand how the web works. Once you render a view and send it to the client, it disconnects from the server. Unless you make AJAX requests to the server, or otherwise retrieve new data from the server, that folder can change all day long, but the client will not be aware of it.

Your entire design should change. You should have an Action which can return a value indicating if the folder changed, and client code to retrieve that data and act on it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: