ASP.NET Core Model Binding Not Working for No Apparent Reason

153 Views Asked by At

I am trying to bind a model to a view (more specifically, a partial view). When I debug the code, I can clearly see the correct object being passed to the view, but in browser DevTools, I see the response as an empty form. I do get a view, but the model is not bound to it, so the form is empty.

For your reference, here is the partial view code:

@model MyApp.Models.Company

<form  method="post" id="editForm" enctype="multipart/form-data">

    <div class="form-group">
        <label asp-for="Name" class="control-label"></label> <span style="color:red;">*</span>
        <input asp-for="Name" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="IsActive" class="control-label"></label>
        <input type="checkbox" asp-for="IsActive" class="form-check-input" style="display: block;" value="true" />
    </div>

    <input type="hidden" asp-for="Id" />
    <div id="errorContainer" style="color:red; background-color: #ffedf0; border-radius: 0.25rem;"></div>

</form>

And here is the controller action that handles request and returns the partial view. Mind you, the exact same code works on another project:

public IActionResult EditPopup(Guid id) // returns `edit` partial view
{
    try
    {
        var model = _context.Companies.Where(x => x.Id.ToString() == id.ToString()).FirstOrDefault();

        if (model == null)
            return Problem(statusCode: 400, detail: "Bad Request"); // 400 Bad Request

        return PartialView("_EditPartial", model);
    }
    catch (Exception ex)
    {
        // TODO logla
        return Problem(statusCode: 500, detail: "An unexpected error happened"); // 500 Internal Server Error
    }
}

I get no errors anywhere. No errors in VS or in browser console. Nothing gets logged to "output" window in VS either. Also, changing debug > exception settings to break on all exceptions did nothing either, so it seems like no exceptions are being thrown anywhere.

Why could model binding be failing? What am I missing?

1

There are 1 best solutions below

0
Emre Bener On

This happened because the project was originally a razor pages app and I added controllers and views later with AddControllersWithViews and MapControllerRoute, but apparently the configurations needed don't end there to add MVC to a project, and I also needed to manually create a _ViewImports.cshtml file to import some things.

Create _ViewImports.cshtml directly under Views folder, and inside it, import your model namespace with a @using directive, and also add asp.net core mvc tag helpers. It would look like:

@using MyApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

asp.net tag helpers is needed to make "asp-for" attributes be recognized and handled by the framework. Now model binding will work.