我的视图中有一个名为'divStatus'的div项目,我想从控制器更新,我的意思是,我想将信息附加到div中的现有内容,以便我从控制器执行:
[HttpPost]
public ActionResult PerformDiagnostic(TestsModel model)
{
var script = "$('#divStatus').append('hello World!');";
return JavaScript(script);
}
好的,这是完美的工作,但是当我想做一些更复杂的事情时,它无法正常工作,例如,想象下面的情况:
[HttpPost]
public ActionResult PerformDiagnostic(TestsModel model)
{
var script = string.Empty;
for (int i = 0; i < 10; i++)
{
script = "$('#divStatus').append('" + "<h1>hello World" + i.ToString() + "!</h1>');";
}
return JavaScript(script);
}
显然执行它之后,串起来“hello World9!”被添加到divStatus控件,因为它是最后执行的,所以当使用JavaScript(脚本)返回时,它会向视图打印最后执行的命令。但是如果我想打印每个循环产生的字符串会发生什么?例如,它想要获得以下内容:
你好World0!
你好World1!
你好World2!
你好World3!
你好World4!
你好World5!
你好World6!
你好World7!
你好World8!
你好World9!
我花了很多天试图做到这一点,这是一场噩梦,有谁能告诉我如何获得这种情况的rif?我非常感谢。我试图以某种方式做类似于返回的事情,但我不知道如何告诉视图:“嘿!你必须使用附加的新信息更新div控件!”
我也试过使用signalr框架来做这个,我已经部分阅读了它的教程,但我不明白,我认为没有一个非常简单的小例子显示如何更新控件,例如我的情况,一个div,来自控制器。另外如果信号员专家可以为我提供一个非常简单的信号器示例,我也非常感激。
我使用的是asp.net mvc 4 razor
这是我的真实案例:
控制器:
public bool DoPing(string hostNameOrAddress)
{
bool connectionOk = false;
try
{
System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping();
connectionOk = pinger.Send(hostNameOrAddress).Status == System.Net.NetworkInformation.IPStatus.Success;
}
catch (Exception ex)
{
connectionOk = false;
}
return connectionOk;
}
[HttpPost]
public ActionResult PerformWTGTests(TestsModel model)
{
bool result = false;
using (ConfigContext context = new ConfigContext())
{
List<Machine> mCollection = context.Machines.Where(m => m.TypeId == 1).ToList();
foreach (Machine machine in mCollection)
{
result = this.DoPing(machine.IP);
string res = result ? "PASSED" : "FAILED";
Debug.WriteLine(String.Format("IP: {0} - Result: {1}", machine.IP, res, CultureInfo.InvariantCulture));
// After I obtain the result for each machine I want to update the control in view, in my case a div, saying if it is passed or failed, so I need to do this at each loop for each machine.
// Below I have tried to update control in view using it but no works
ViewBag.JS = "updateProgressWindow('" + machine.IP + "','" + res + "');";
}
}
if (result)
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
}
}
答案 0 :(得分:4)
你做不到。操作方法中的C#代码将始终在执行客户端脚本之前执行。你最好的选择就是在剧本中注入循环:
[HttpPost]
public ActionResult PerformDiagnostic(TestsModel model)
{
var script = "for (var i = 0; i < 10; i++ ) $('#divStatus').append('<h1>hello World' + i + '</h1>');";
return JavaScript(script);
}