Reputation: 1111
I have an ASP.NET application with some web API endpoint.
I want to append the data displayed on the home page every time it is received by the endpoint.
How can I achieve it in the simplest way. I would appreciate any help.
EDIT:
Api Controller:
public class ValuesController : ApiController
{
public static event EventHandler<string> DataPosted;
public IHttpActionResult Get(string value)
{
DataPosted?.Invoke(this, value);
return Ok();
}
}
Home page Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ValuesController.DataPosted += (s_, e_) =>
{
ViewBag.MyData += Environment.NewLine + e_;
};
return View();
}
}
Home page View:
<div class="row">
<div class="col-md-4">
<h2>Output</h2>
<p>@ViewBag.MyData</p>
</div>
</div>
This, of course, doesn't work. I think I need to find a way to force part of the page responsible for displaying @ViewBag.MyData
to refresh. I also tried with partial view but without any luck.
Upvotes: 0
Views: 663
Reputation: 1269
I think the approach to this problem is incorrect.
You have a browser that is making a request to your web app to view the homepage. The web app will serve the homepage to the browser with the contents of ViewBag.MyData.
You have an endpoint ValuesController.Get(string value) and when its called you want it to update the value in ViewBag.MyData and inevitably update the homepage with its contents.
The problems are:
Fixes are:
If the requirement is to persist the value passed into ValuesController.Get(string value) further than the lifetime of the application, then I would highly recommend storing that value in a database somewhere. Values stored in static variables and application variables only live as long as the AppDomain does (if you restart your web app, or close it, those values or lost, but in a database, its still there).
Upvotes: 2