2

I'm trying to build a very simple website to display some test data being added & updated using asp.net mvc (with razor) but whenever data is posted to my Post method, my data is not being updated. I'm trying to get a unordered list (for now) to be updated the second a post is triggered.

I'm posting my data as JSON using the following code:

string jsonDeviceData = SerializeHelper.Serialize<IDeviceData>(deviceData, 
                        ContentTypeEnum.Json, false);

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(localServerUrl);
webRequest.Method = "POST";
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";

byte[] deviceDataBuffer = Encoding.UTF8.GetBytes(jsonDeviceData);

Task<Stream> requestTask = webRequest.GetRequestStreamAsync();
using (Stream requestStream = requestTask.Result)
{
    requestStream.Write(deviceDataBuffer, 0, deviceDataBuffer.Length);
}

Task<WebResponse> responseTask = webRequest.GetResponseAsync();
using (StreamReader requestReader = new StreamReader(responseTask.Result
           .GetResponseStream()))
{
    string webResponse = requestReader.ReadToEnd();
    Debug.WriteLine("Web Response: " + webResponse);
}

Below is the code I'm using in the POST method. Don't worry about the logic being so simplistic and probably horrible, but I'm just dabbling with this idea. Data will be stored in SQL Server database and I'll use EF if I decide to go further with this:

[HttpPost()]
public ActionResult Index(DeviceModel model)
{
    if (ModelState.IsValid && model != null)
    {
        var deviceViewModelList = HttpContext.Application["DeviceList"] 
            as List<DeviceViewModel> ?? new List<DeviceViewModel>();

        if (deviceViewModelList.All(m => !string.Equals(m.Name,
                    model.Name, 
                    StringComparison.InvariantCultureIgnoreCase)))
        {
            deviceViewModelList.Add(new DeviceViewModel(model));
        }

        HttpContext.Application["DeviceList"] = deviceViewModelList;

        var homePageViewModel = new HomePageViewModel
        {
            DeviceList = deviceViewModelList
        };

        return RedirectToAction("Index");
    }
    else
    {
        return View();
    }
}

My model is passed correctly and everything works ok when the data is posted my page is not updated, even after calling RedirectToAction("Index");

The code below gets called the first time the page is loaded and after calling the RedirectToActio("Index"):

public ActionResult Index()
{
    ViewBag.Title = "Test Server";

    var deviceViewModelList = HttpContext.Application["DeviceList"] 
        as List<DeviceViewModel> ?? new List<DeviceViewModel>();

    var homePageViewModel = new HomePageViewModel
    {
        DeviceList = deviceViewModelList
    };

    return View(homePageViewModel);
}

This is the code I have in my .cshtml page:

<ul>
    @if (Model?.DeviceList != null)
    {
        foreach (var device in Model.DeviceList)
        {
            <li>@device.Name</li>
        }
    }
</ul>
  • If I check Fiddler, the data, in this case, the list is build correctly.
  • If I press F5 my data is displayed correctly.

I've read so many articles at this stage and I still haven't got a solution, one of them being View not updated after post and while I've tried ModelState.Clear(); and as you can see from my code I'm using @device.Name which is one of the suggestion. I'm not sure about the last one.

Another article I read was ASP NET MVC Post Redirect Get Pattern but again to no avail.

I'm obviously missing something.

Most articles/samples I've been looking at refer to posting via a Form and I know I'm posting, but is that the same as posting via a Form?

Also my page's viewModel is for my page and it contains a list of devices. Is that OK rather than passing the list of device as the viewmodel to the page? The reason I'm doing this is that I will want to access other lists at a later stage.

Has anyone got any suggestions?

Much appreciated.

Community
  • 1
  • 1
Thierry
  • 6,142
  • 13
  • 66
  • 117

0 Answers0