I am trying to create a webpage using MVC that dynamically changes based on httprequests received from ac# application. The c# application is sending an httpPost to the webpage, which is being received by the MVC controller's Index action.
The httpPost sent by the c# application:
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);
here is the MVC controller: 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();
}
}
}
and the view: Index.cshtml
@{
ViewBag.Title = "Home Page";
}
@{
string packet = ViewBag.PacketText;
}
<div>
<h3 id="packetDisplay">@packet</h3>
</div>
When the webpage is launched, the page reads "none" as it should. when the c# application is run, and the httpPost request is sent to the webpage, the Index action receives it and changes the ViewBag.PacketText. I debugged the view in VS and the packet variable is being changed to "Packet", but the webpage in the browser still reads "none" and never gets changed. What do I need to do to make the webpage update when PacketText changes?
You should see the packet variable changed to "Packet" in the response sent to your C# application . To see the change in browser you need to send POST requiest from the browser itself.
Add following in the cshtml page (note: I have not checked, there may be errors):
<form action="" method="post">
<input name="Packet" type="hidden" value="Something">
<input type="submit" value="Submit">
</form>
When clicking on the Submit button you should see "Something" instead of none.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.