视图中的ASP.Net MVC动态文本未更新页面

时间:2019-01-08 21:44:30

标签: c# asp.net-mvc model-view-controller

我正在尝试使用MVC创建一个网页,该网页会根据从C#应用程序收到的httprequests进行动态更改。 C#应用程序正在将httpPost发送到网页,MVC控制器的Index操作正在接收该httpPost。

c#应用程序发送的httpPost:

HttpClient _SendClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Packet", "none")
            };
            HttpContent content = new FormUrlEncodedContent(pairs);
            HttpResponseMessage result = await _SendClient.PostAsync("http://localhost:53056", content);

这是MVC控制器:HomeController.cs

namespace WebApplication2.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      { 

         string[] keys = Request.Form.AllKeys;
         if (keys.Length > 0) //received packet
         {
            ViewBag.PacketText = keys[0];
         }
         else
         {
            ViewBag.PacketText = "none";
         }
         return View();
      }
   }
}

和视图:Index.cshtml

@{
   ViewBag.Title = "Home Page";
}

@{
   string packet = ViewBag.PacketText;
}

<div>
     <h3 id="packetDisplay">@packet</h3>
</div>

启动网页后,该页面应显示为“ none”。当运行c#应用程序并将httpPost请求发送到网页时,Index操作将收到该请求并更改ViewBag.PacketText。我在VS中调试了视图,然后将packet变量更改为“ Packet”,但浏览器中的网页仍显示为“ none”,并且从未更改。 PacketText更改时,我该怎么做才能使网页更新?

1 个答案:

答案 0 :(得分:0)

您应该在发送到您的C#应用​​程序的响应中看到数据包变量已更改为“数据包”。要查看浏览器中的更改,您需要从浏览器本身发送POST请求。

在cshtml页面中添加以下内容(注意:我尚未检查,可能有错误):

<form action="" method="post">
    <input name="Packet" type="hidden" value="Something">
    <input type="submit" value="Submit">
</form>

单击“提交”按钮时,您应该看到“有什么东西”,而不是无。