LeViNcE
LeViNcE

Reputation: 314

MVC Error on Displaying Data From Web API

I am new to ASP.NET programming and I encounter some problem, maybe someone can help me to find the solution.

I followed and completed the procedure here BeginForm with IEnumerable. But when I tried to run my codes. Something error happens on browser. The error is:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ek_oms.Models.AddCategoryViewModel]', but this dictionary requires a model item of type 'ek_oms.Models.AddCategoryViewModel'.

Here's my related codes to that part.

Class:

public class AddCategoryViewModel
{
    public IEnumerable<CategoryViewModel> CurrentCategories { get; set; }
    public CategoryModel NewCategory { get; set; }
}

Partial codes in View:

@model ek_oms.Models.AddCategoryViewModel
@if (Model.CurrentCategories != null)
{
    foreach (var item in Model.CurrentCategories)
    {
        <tr>
            <td>@item.CategoryName</td>
            <td>
                @using (Html.BeginForm("CategoryDelete", "Admin", new { catID = item.Id }, FormMethod.Post, null))
                {
                    @Html.AntiForgeryToken()
                    @Html.ActionLink("Edit", "CategoryEdit", null, new { catID = item.Id }, new { @class = "btn btn-primary btn-xs" })
                    <button type="submit" class="btn btn-danger btn-xs" onclick="return confirm('Are you sure you want to delete record with Category = @item.CategoryName')">Delete</button>}
            </td>
        </tr>
    }
}

<div class="tab-content">
    @using (Html.BeginForm("Categories", "Admin", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
    {
        @Html.AntiForgeryToken()
        <div class="box box-primary">
            <!-- /.box-header -->
            <div class="box-body">
                <div class="box-header">
                    <h3 class="box-title">Add New Category</h3>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            @Html.EditorFor(model => model.NewCategory.CategoryName, new { htmlAttributes = new { @class = "form-control", id = "Category", @placeholder = @Html.DisplayNameFor(model => model.NewCategory.CategoryName) } })
                            @Html.ValidationMessageFor(model => model.NewCategory.CategoryName, "", new { @class = "text-danger" })
                        </div>
                        <div class="form-group">
                        </div>
                    </div>
                </div>
            </div>
            <div class="box-footer">
                <button type="submit" class="btn btn-primary" id="submitAddCatBtn">Add</button>
            </div>
        </div>
    }
</div>

Controller:

public async Task<ActionResult> Categories()
{
    ViewBag.Message = TempData["Message"];
    ViewBag.CatUsedMessage = TempData["CatUsedMessage"];

    HttpResponseMessage responseMessage = await client.GetAsync(urlProducts + "/categories");
    if (responseMessage.IsSuccessStatusCode)
    {
        var responseData = responseMessage.Content.ReadAsStringAsync().Result;
        var categories = JsonConvert.DeserializeObject<List<AddCategoryViewModel>>(responseData);
        return View(categories);
    }
    return View("Error");
}

Can someone help me to this. I don't know the right term to start searching. Thanks.

Upvotes: 0

Views: 114

Answers (1)

User3250
User3250

Reputation: 3423

var categories = JsonConvert.DeserializeObject<List<AddCategoryViewModel>>(responseData);

Above line is the issue.

Your view is expecting just one AddCategoryViewModel object and not a List<AddCategoryViewModel>. As the error message clearly suggests.

So, change your code to return only one object if you are expecting just one from the api as below:

var categories = JsonConvert.DeserializeObject<AddCategoryViewModel>(responseData);

OR if you need more than one category Change your @model in view as below:

@model List<ek_oms.Models.AddCategoryViewModel>

In this case you will need to change your view code to handle Category list accordingly as below:

@foreach(var cat in Model)
{
    if (cat != null)//use cat in place of Model in your view
    {
      foreach (var item in cat.CurrentCategories)
      {
      }
    }
}

Upvotes: 1

Related Questions