0

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.

1 Answer 1

1
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)
      {
      }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I update my code and modify my view to your second suggestion @model List<ek_oms.Models.AddCategoryViewModel>,how can I change my view code to handle Category list? because the error is in that part now? thanks anyways to your answer :)
The error is now on my beginform? How can I fix that? thanks.
List<AddCategoryViewModel>' does not contain a definition for 'NewCategory' and no extension method 'NewCategory' accepting a first argument of type 'List<AddCategoryViewModel>' could be found (are you missing a using directive or an assembly reference?). Its on part of my html.editorfor
You need to understand what is going on here. You would find answers yourself. Check here
I've tried to comment out first my html.editorfor,,and here's another error. In this part foreach (var item in cat.CurrentCategories) i've got the error System.NullReferenceException: 'Object reference not set to an instance of an object.'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.