最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net core mvc - Model is null on POST to controller as soon I add one more column in a table - Stack Overflow

programmeradmin4浏览0评论

I'm trying to load an XML file on a table to display each values and maybe edit them prior to loading it into the database.

The class has over 50 properties. Everything works fine with 34 properties. As soon as I add 1 more column in the table + class regardless of the type (string, int, bool etc) the view model is NULL on POST.

The binding seems correct using an indexed "FOR" loop and not a "Foreach". I have an Input for each column. Not sure why adding 1 column would cause the issue. Would really appreciate the help.

This is my controller code

[HttpGet]
[Authorize(Roles = "SuperAdmin,Dealer")]
public ViewResult EquipmentImport(string dealer_id)
{
    // Decrypt the id using Unprotect method
    string decryptedId = "";
    decryptedId = _protector.Unprotect(dealer_id);

    Dealer d = _dealerRepository.GetDealer(decryptedId);

    if (d == null)
    {
        Response.StatusCode = 404;
        return View("NotFound", "Dealer ID = " + dealer_id + " could not be found.");//in the Shared Folder
    }

    d.EncryptedId = dealer_id;

    EquipmentListImportViewModel viewmodel = new EquipmentListImportViewModel();
    viewmodel.EquipmentList = null;
    viewmodel.EncryptedDealer_Id = dealer_id;
    viewmodel.Dealer_Name = d.Dealer_Name;

    return View(viewmodel);
}

[HttpPost]
[Authorize(Roles = "SuperAdmin,Dealer")]
public async Task<IActionResult> EquipmentImport(EquipmentListImportViewModel viewmodel, IFormFile? batchEquipmentFile, string submit)
{
    var userlogged = await GetCurrentUserAsync();
    string decryptedId = _protector.Unprotect(viewmodel.EncryptedDealer_Id);

    Dealer d = _dealerRepository.GetDealer(decryptedId);

    if (d == null)
    {
        Response.StatusCode = 404;
        return View("NotFound", "Dealer ID = " + decryptedId + " could not be found.");//in the Shared Folder
    }

    d.EncryptedId = d.EncryptedId;

    viewmodel.EncryptedDealer_Id = d.EncryptedId;
    viewmodel.Dealer_Name = d.Dealer_Name;

    List<Make_Mapping> make_Mappings = _make_mappingRepository.GetAllMake_Mappings(d.Dealer_Id).ToList();
    List<Group_Mapping> group_Mappings = _group_mappingRepository.GetAllGroup_Mappings(d.Dealer_Id).ToList();
    List<Mhhr_equipment_2> equipmentList = new List<Mhhr_equipment_2>();

    Debug.WriteLine(ModelState.IsValid);

    switch (submit)
    {
        case "uploadEquipmentFile":
            // Wrap the code in a try/catch block
            if (batchEquipmentFile == null)
            {
                return View(viewmodel);
            }

            try
            {
                using (var stream = batchEquipmentFile.OpenReadStream())
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Mhhr_equipment_2>));
                    var deserializedList = serializer.Deserialize(stream) as List<Mhhr_equipment_2>;
                    if (deserializedList != null)
                    {
                        equipmentList = deserializedList;
                    }
                    else
                    {
                        // Handle the case where deserialization returns null
                        equipmentList = new List<Mhhr_equipment_2>();
                    }
                }

                foreach (var item in equipmentList)
                {
                    bool makeexist = false;
                    makeexist = make_Mappings.Any(a => a.Dealer_Make_Id == item.Make_Id);

                    if (!makeexist)
                    {
                        item.Error_Found += "No Mapping Found For the Make = " + item.Make_Id + " in our system. Please review your make Mapping or contact support.";
                    }
                }

                foreach (var item in equipmentList)
                {
                    bool groupexist = false;
                    groupexist = group_Mappings.Any(a => a.Dealer_Group_Id == item.Group_Id);

                    if (!groupexist)
                    {
                        item.Error_Found += "No Mapping Found For the Group = " + item.Group_Id + " in our system. Please review your Group Mapping or contact support.";
                    }
                }

                viewmodel.EquipmentList = equipmentList.ToList();
                return View(viewmodel);
            }
            catch (Exception ex)
            {
                // Log the exception to a file.We discussed logging to a file
                // using Nlog in Part 63 of ASP.NET Core tutorial
                _logger.LogError($"Exception Occured : {ex}");
                // Pass the ErrorTitle and ErrorMessage that you want to show to
                // the user using ViewBag. The Error view retrieves this data
                // from the ViewBag and displays to the user.
                ViewBag.ErrorTitle = "Error importing equipment";
                ViewBag.ErrorMessage = "An error occurred while importing the equipment data.";
                return View("Error");
            }

        case "LoadEquipmentFile":
            foreach (var item in viewmodel.EquipmentList)
            {
                //Code here would be to add the equipment to the database
                if (newequ)
                {
                    s = _equipmentRepository.Add(s, userlogged.Id);
                }
                else
                {
                    s = _equipmentRepository.Update(s, userlogged.Id);
                }
            }

            if (string.IsNullOrWhiteSpace(ViewBag.ErrorMessage))
            {
                TempData["MyMessage"] = "Your records were loaded Successfully !";
                return RedirectToAction("EquipmentDealerIndex", new { dealer_id = viewmodel.EncryptedDealer_Id, message = "Success" });
            }
            else
            {
                TempData["MyMessage"] = "Your records were loaded with errors !" + Environment.NewLine + ViewBag.ErrorMessage;
                return RedirectToAction("EquipmentDealerIndex", new { dealer_id = viewmodel.EncryptedDealer_Id, message = "Error" });
            }
    }

    return View(viewmodel);
}

The code for the model:

public class EquipmentListImportViewModel
{
    public List<Mhhr_equipment_2>? EquipmentList { get; set; }
    public string? EncryptedDealer_Id { get; set; }
    public string? Dealer_Name { get; set; }
}

The code for the class Mhhr_equipment_2:

public class Mhhr_equipment_2:BaseModel
{
    [Required]
    public string Mhhr_Dealer_Key { get; set; }

    [Display(Name = "Error")]
    public string? Error_Found { get; set; }

    [Display(Name = "Group Id")]
    [Required]
    [MaxLength(10, ErrorMessage = "Field cannot be more than 10 Characters")]
    public string Group_Id { get; set; }

    [Display(Name = "Serial #")]
    [Required]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string Equipment_SerialNumber { get; set; }

    [Display(Name = "Make")]
    [Required]
    [MaxLength(4, ErrorMessage = "Field cannot be more than 4 Characters")]
    public string Make_Id { get; set; }

    [Display(Name = "Model Id")]
    [Required]
    [MaxLength(25, ErrorMessage = "Field cannot be more than 25 Characters")]
    public string Model_Id { get; set; }

    [Display(Name = "Dealer Id")]
    [Required]
    [MaxLength(25, ErrorMessage = "Field cannot be more than 25 Characters")]
    public string Equipment_Dealer_Id { get; set; }

    [Display(Name = "Dealer Equip PK Id")]
    [Required]
    [MaxLength(36, ErrorMessage = "Field cannot be more than 36 Characters")]
    public string Equipment_Dealer_PKId { get; set; }

    [Display(Name = "Hours")]
    [Required]
    public decimal Equipment_UsageHours { get; set; }

    [Display(Name = "Serie")]
    [MaxLength(15, ErrorMessage = "Field cannot be more than 15 Characters")]
    public string Equipment_Serie { get; set; }

    [Display(Name = "Plate")]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string? Equipment_Plate { get; set; }

    [Display(Name = "Description")]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string Equipment_Desc { get; set; }

    [Display(Name = "Notes")]
    public string? Equipment_Notes { get; set; }

    [Display(Name = "D. First Used")]
    public DateTime? Equipment_D_FirstUsed { get; set; }

    [Display(Name = "Year Manu")]
    public int Equipment_Year_Manufactured { get; set; }

    [Display(Name = "Photo 1")]
    public string? Equipment_Photo1 { get; set; }

    [Display(Name = "Photo 2")]
    public string? Equipment_Photo2 { get; set; }

    [Display(Name = "Photo 3")]
    public string? Equipment_Photo3 { get; set; }

    [Display(Name = "Photo 4")]
    public string? Equipment_Photo4 { get; set; }

    [Display(Name = "Photo 5")]
    public string? Equipment_Photo5 { get; set; }

    [Display(Name = "Photo 6")]
    public string? Equipment_Photo6 { get; set; }

    [Display(Name = "Photo 7")]
    public string? Equipment_Photo7 { get; set; }

    [Display(Name = "Photo 8")]
    public string? Equipment_Photo8 { get; set; }

    [Display(Name = "Photo 9")]
    public string? Equipment_Photo9 { get; set; }

    [Display(Name = "Photo 10")]
    public string? Equipment_Photo10 { get; set; }

    //ATTACHMENT OPTIONS
    #region OPTION Attachment
    [Display(Name = "Attach. Type")]
    public string? Equipment_Opt_Attach_Type { get; set; }

    [Display(Name = "Capacity")]
    public int? Equipment_Opt_Attach_Capacity { get; set; }

    [Display(Name = "Attach. Size")]
    public int? Equipment_Opt_Attach_Size { get; set; }
    #endregion OPTION Attachment
    //END ATTACHMENT

    //ELECTRICAL
    #region OPTION ELECTRICAL
    [Display(Name = "Elec. Volt")]
    public int? Equipment_Opt_Electrical_Volt { get; set; }

    [Display(Name = "Elec. AMP")]
    public decimal? Equipment_Opt_Electrical_AMP { get; set; }

    [Display(Name = "Elec. Capacity")]
    public int? Equipment_Opt_Electrical_Capacity { get; set; }

    [Display(Name = "Elec. Lift Limit")]
    public int? Equipment_Opt_Electrical_Lift_Limit { get; set; }

    [Display(Name = "Elec. Keyless")]
    public bool Equipment_Opt_Electrical_Keyless { get; set; }

    [Display(Name = "Elec. Wireguide")]
    public bool Equipment_Opt_Electrical_Wireguide { get; set; }

    //[Display(Name = "Elec. Alarm")]
    //public bool Equipment_Opt_Electrical_Alarm { get; set; }

    //[Display(Name = "Elec. Light/Fan PKG")]
    //public bool Equipment_Opt_Electrical_Light_Fan_Pkg { get; set; }

    //[Display(Name = "Elec. Work Lights")]
    //public bool Equipment_Opt_Electrical_Work_Lights { get; set; }
    #endregion OPTION ELECTRICAL

    //END ELECTRICAL

    #region OPTION MAST
    [Display(Name = "Mast OACH")]
    public int? Equipment_Opt_Mast_Oach { get; set; }

    [Display(Name = "Elevated Height")]
    public int? Equipment_Opt_Mast_Elevated_Height { get; set; }

    #endregion OPTION MAST
}

And finally the view itself:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@model EquipmentListImportViewModel

@{
    var mymessage = "";

    if (TempData.ContainsKey("MyMessage"))
    {
        mymessage = TempData["MyMessage"] as string;
    }
}

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <form asp-controller="Equipments" asp-action="EquipmentImport" method="post" enctype="multipart/form-data">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <div class="container-fluid">
            </div><!-- /.container-fluid -->
        </section>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <h3 class="card-title">@Localizer["List of Equipment For"] @Model.Dealer_Name</h3>

                    <input asp-for="@Model.EncryptedDealer_Id" class="form-control " hidden />

                    @if (Model.EquipmentList != null)
                    {
                        <div class="row col-2">
                            @if (string.IsNullOrWhiteSpace(mymessage))
                            {
                                <div class="input-group">
                                    <button type="submit" class="btn btn-outline-info" name="submit" value="LoadEquipmentFile">
                                        @Localizer["Load Data"]
                                    </button>
                                </div>
                            }
                            else
                            {
                                <a asp-controller="Equipments" asp-action="EquipmentImport" asp-route-dealer_Id="@Model.EncryptedDealer_Id" class="btn btn-info ">
                                    @Localizer["Equip. Import"]
                                </a>
                            }
                            <br />
                        </div>
                        @if (!string.IsNullOrWhiteSpace(mymessage))
                        {
                            <h3 class="card-title text-bg-danger">@mymessage</h3>  <!-- DISPLAY ERROR MESSAGE -->
                        }
                    }
                    else
                    {
                        <div class="row col-6">
                            <div class="custom-file">
                                <input id="batchEquipmentFile" name="batchEquipmentFile" class="form-control" type="file" aria-describedby="batchEquipmentFile" accept=".xml">
                            </div>

                            <div class="input-group">
                                <button type="submit" class="btn btn-outline-info" name="submit" value="uploadEquipmentFile">
                                    @Localizer["Upload"]
                                </button>
                            </div>
                        </div>
                    }

                    @if (Model.EquipmentList != null)
                    {
                        <table id="example1" class="table table-hover table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th hidden>Dealer</th>
                                    <th>Error</th>
                                    <th>Group_Id</th>
                                    <th>Equipment_Desc</th>
                                    <th>Make_Id</th>
                                    <th>Model_Id</th>
                                    <th>Equipment_SerialNumber</th>
                                    <th>Equipment_Serie</th>
                                    <th>Equipment_Dealer_Id</th>
                                    <th>Equipment_Dealer_PKId</th>
                                    <th>Equipment_UsageHours</th>
                                    <th>Equipment_Plate</th>
                                    <th>Equipment_Notes</th>
                                    <th>Equipment_D_FirstUsed</th>
                                    <th>Equipment_Year_Manufactured</th>
                                    <th>Equipment_Photo1</th>
                                    <th>Equipment_Photo2</th>
                                    <th>Equipment_Photo3</th>
                                    <th>Equipment_Photo4</th>
                                    <th>Equipment_Photo5</th>
                                    <th>Equipment_Photo6</th>
                                    <th>Equipment_Photo7</th>
                                    <th>Equipment_Photo8</th>
                                    <th>Equipment_Photo9</th>
                                    <th>Equipment_Photo10</th>
                                    <th>Equipment_Opt_Attach_Type</th>
                                    <th>Equipment_Opt_Attach_Capacity</th>
                                    <th>Equipment_Opt_Attach_Size</th>
                                    <th>Equipment_Opt_Electrical_Volt</th>
                                    <th>Equipment_Opt_Electrical_AMP</th>
                                    <th>Equipment_Opt_Electrical_Capacity</th>
                                    <th>Equipment_Opt_Electrical_Lift_Limit</th>
                                    <th>Equipment_Opt_Electrical_Keyless</th>
                                    <th>Equipment_Opt_Electrical_Wireguide</th>

                                    <th>Equipment_Opt_Mast_Oach</th>
                                    <th>Equipment_Opt_Mast_Elevated_Height</th>

                                </tr>
                            </thead>

                            <tbody>

                                @for (int i = 0; i < Model.EquipmentList.Count; i++)
                                {
                                    <!-- LOOP MUST BE WITH FOR i and each have an input type hidden/read only otherwise, it's not returned back to the viewmodel on POST -->
                                    <tr>
                                        <td hidden><input type="text" asp-for="@Model.EquipmentList[i].Mhhr_Dealer_Key" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Error_Found" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Group_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Desc" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Make_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Model_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_SerialNumber" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Serie" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Dealer_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Dealer_PKId" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_UsageHours" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Plate" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Notes" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_D_FirstUsed" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Year_Manufactured" class="form-control"></td>
                                        <td><input readonly type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo1" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo2" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo3" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo4" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo5" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo6" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo7" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo8" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo9" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo10" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Type" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Capacity" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Size" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Volt" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_AMP" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Capacity" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Lift_Limit" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Keyless" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Wireguide" class="form-control"></td>

                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Mast_Oach" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Mast_Elevated_Height" class="form-control"></td>

                                    </tr>
                                }

                            </tbody>

                            <tfoot>
                                <tr>
                                </tr>
                            </tfoot>
                        </table>
                    }



                </div>
                <!-- /.row -->
            </div>
            <!-- /.container-fluid -->
        </section>
        <!-- /.content -->

    </form>
</div>
<!-- /.content-wrapper -->
<!-- page script -->
@section Scripts {
    <script>
    </script>
}

I'm trying to load an XML file on a table to display each values and maybe edit them prior to loading it into the database.

The class has over 50 properties. Everything works fine with 34 properties. As soon as I add 1 more column in the table + class regardless of the type (string, int, bool etc) the view model is NULL on POST.

The binding seems correct using an indexed "FOR" loop and not a "Foreach". I have an Input for each column. Not sure why adding 1 column would cause the issue. Would really appreciate the help.

This is my controller code

[HttpGet]
[Authorize(Roles = "SuperAdmin,Dealer")]
public ViewResult EquipmentImport(string dealer_id)
{
    // Decrypt the id using Unprotect method
    string decryptedId = "";
    decryptedId = _protector.Unprotect(dealer_id);

    Dealer d = _dealerRepository.GetDealer(decryptedId);

    if (d == null)
    {
        Response.StatusCode = 404;
        return View("NotFound", "Dealer ID = " + dealer_id + " could not be found.");//in the Shared Folder
    }

    d.EncryptedId = dealer_id;

    EquipmentListImportViewModel viewmodel = new EquipmentListImportViewModel();
    viewmodel.EquipmentList = null;
    viewmodel.EncryptedDealer_Id = dealer_id;
    viewmodel.Dealer_Name = d.Dealer_Name;

    return View(viewmodel);
}

[HttpPost]
[Authorize(Roles = "SuperAdmin,Dealer")]
public async Task<IActionResult> EquipmentImport(EquipmentListImportViewModel viewmodel, IFormFile? batchEquipmentFile, string submit)
{
    var userlogged = await GetCurrentUserAsync();
    string decryptedId = _protector.Unprotect(viewmodel.EncryptedDealer_Id);

    Dealer d = _dealerRepository.GetDealer(decryptedId);

    if (d == null)
    {
        Response.StatusCode = 404;
        return View("NotFound", "Dealer ID = " + decryptedId + " could not be found.");//in the Shared Folder
    }

    d.EncryptedId = d.EncryptedId;

    viewmodel.EncryptedDealer_Id = d.EncryptedId;
    viewmodel.Dealer_Name = d.Dealer_Name;

    List<Make_Mapping> make_Mappings = _make_mappingRepository.GetAllMake_Mappings(d.Dealer_Id).ToList();
    List<Group_Mapping> group_Mappings = _group_mappingRepository.GetAllGroup_Mappings(d.Dealer_Id).ToList();
    List<Mhhr_equipment_2> equipmentList = new List<Mhhr_equipment_2>();

    Debug.WriteLine(ModelState.IsValid);

    switch (submit)
    {
        case "uploadEquipmentFile":
            // Wrap the code in a try/catch block
            if (batchEquipmentFile == null)
            {
                return View(viewmodel);
            }

            try
            {
                using (var stream = batchEquipmentFile.OpenReadStream())
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Mhhr_equipment_2>));
                    var deserializedList = serializer.Deserialize(stream) as List<Mhhr_equipment_2>;
                    if (deserializedList != null)
                    {
                        equipmentList = deserializedList;
                    }
                    else
                    {
                        // Handle the case where deserialization returns null
                        equipmentList = new List<Mhhr_equipment_2>();
                    }
                }

                foreach (var item in equipmentList)
                {
                    bool makeexist = false;
                    makeexist = make_Mappings.Any(a => a.Dealer_Make_Id == item.Make_Id);

                    if (!makeexist)
                    {
                        item.Error_Found += "No Mapping Found For the Make = " + item.Make_Id + " in our system. Please review your make Mapping or contact support.";
                    }
                }

                foreach (var item in equipmentList)
                {
                    bool groupexist = false;
                    groupexist = group_Mappings.Any(a => a.Dealer_Group_Id == item.Group_Id);

                    if (!groupexist)
                    {
                        item.Error_Found += "No Mapping Found For the Group = " + item.Group_Id + " in our system. Please review your Group Mapping or contact support.";
                    }
                }

                viewmodel.EquipmentList = equipmentList.ToList();
                return View(viewmodel);
            }
            catch (Exception ex)
            {
                // Log the exception to a file.We discussed logging to a file
                // using Nlog in Part 63 of ASP.NET Core tutorial
                _logger.LogError($"Exception Occured : {ex}");
                // Pass the ErrorTitle and ErrorMessage that you want to show to
                // the user using ViewBag. The Error view retrieves this data
                // from the ViewBag and displays to the user.
                ViewBag.ErrorTitle = "Error importing equipment";
                ViewBag.ErrorMessage = "An error occurred while importing the equipment data.";
                return View("Error");
            }

        case "LoadEquipmentFile":
            foreach (var item in viewmodel.EquipmentList)
            {
                //Code here would be to add the equipment to the database
                if (newequ)
                {
                    s = _equipmentRepository.Add(s, userlogged.Id);
                }
                else
                {
                    s = _equipmentRepository.Update(s, userlogged.Id);
                }
            }

            if (string.IsNullOrWhiteSpace(ViewBag.ErrorMessage))
            {
                TempData["MyMessage"] = "Your records were loaded Successfully !";
                return RedirectToAction("EquipmentDealerIndex", new { dealer_id = viewmodel.EncryptedDealer_Id, message = "Success" });
            }
            else
            {
                TempData["MyMessage"] = "Your records were loaded with errors !" + Environment.NewLine + ViewBag.ErrorMessage;
                return RedirectToAction("EquipmentDealerIndex", new { dealer_id = viewmodel.EncryptedDealer_Id, message = "Error" });
            }
    }

    return View(viewmodel);
}

The code for the model:

public class EquipmentListImportViewModel
{
    public List<Mhhr_equipment_2>? EquipmentList { get; set; }
    public string? EncryptedDealer_Id { get; set; }
    public string? Dealer_Name { get; set; }
}

The code for the class Mhhr_equipment_2:

public class Mhhr_equipment_2:BaseModel
{
    [Required]
    public string Mhhr_Dealer_Key { get; set; }

    [Display(Name = "Error")]
    public string? Error_Found { get; set; }

    [Display(Name = "Group Id")]
    [Required]
    [MaxLength(10, ErrorMessage = "Field cannot be more than 10 Characters")]
    public string Group_Id { get; set; }

    [Display(Name = "Serial #")]
    [Required]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string Equipment_SerialNumber { get; set; }

    [Display(Name = "Make")]
    [Required]
    [MaxLength(4, ErrorMessage = "Field cannot be more than 4 Characters")]
    public string Make_Id { get; set; }

    [Display(Name = "Model Id")]
    [Required]
    [MaxLength(25, ErrorMessage = "Field cannot be more than 25 Characters")]
    public string Model_Id { get; set; }

    [Display(Name = "Dealer Id")]
    [Required]
    [MaxLength(25, ErrorMessage = "Field cannot be more than 25 Characters")]
    public string Equipment_Dealer_Id { get; set; }

    [Display(Name = "Dealer Equip PK Id")]
    [Required]
    [MaxLength(36, ErrorMessage = "Field cannot be more than 36 Characters")]
    public string Equipment_Dealer_PKId { get; set; }

    [Display(Name = "Hours")]
    [Required]
    public decimal Equipment_UsageHours { get; set; }

    [Display(Name = "Serie")]
    [MaxLength(15, ErrorMessage = "Field cannot be more than 15 Characters")]
    public string Equipment_Serie { get; set; }

    [Display(Name = "Plate")]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string? Equipment_Plate { get; set; }

    [Display(Name = "Description")]
    [MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
    public string Equipment_Desc { get; set; }

    [Display(Name = "Notes")]
    public string? Equipment_Notes { get; set; }

    [Display(Name = "D. First Used")]
    public DateTime? Equipment_D_FirstUsed { get; set; }

    [Display(Name = "Year Manu")]
    public int Equipment_Year_Manufactured { get; set; }

    [Display(Name = "Photo 1")]
    public string? Equipment_Photo1 { get; set; }

    [Display(Name = "Photo 2")]
    public string? Equipment_Photo2 { get; set; }

    [Display(Name = "Photo 3")]
    public string? Equipment_Photo3 { get; set; }

    [Display(Name = "Photo 4")]
    public string? Equipment_Photo4 { get; set; }

    [Display(Name = "Photo 5")]
    public string? Equipment_Photo5 { get; set; }

    [Display(Name = "Photo 6")]
    public string? Equipment_Photo6 { get; set; }

    [Display(Name = "Photo 7")]
    public string? Equipment_Photo7 { get; set; }

    [Display(Name = "Photo 8")]
    public string? Equipment_Photo8 { get; set; }

    [Display(Name = "Photo 9")]
    public string? Equipment_Photo9 { get; set; }

    [Display(Name = "Photo 10")]
    public string? Equipment_Photo10 { get; set; }

    //ATTACHMENT OPTIONS
    #region OPTION Attachment
    [Display(Name = "Attach. Type")]
    public string? Equipment_Opt_Attach_Type { get; set; }

    [Display(Name = "Capacity")]
    public int? Equipment_Opt_Attach_Capacity { get; set; }

    [Display(Name = "Attach. Size")]
    public int? Equipment_Opt_Attach_Size { get; set; }
    #endregion OPTION Attachment
    //END ATTACHMENT

    //ELECTRICAL
    #region OPTION ELECTRICAL
    [Display(Name = "Elec. Volt")]
    public int? Equipment_Opt_Electrical_Volt { get; set; }

    [Display(Name = "Elec. AMP")]
    public decimal? Equipment_Opt_Electrical_AMP { get; set; }

    [Display(Name = "Elec. Capacity")]
    public int? Equipment_Opt_Electrical_Capacity { get; set; }

    [Display(Name = "Elec. Lift Limit")]
    public int? Equipment_Opt_Electrical_Lift_Limit { get; set; }

    [Display(Name = "Elec. Keyless")]
    public bool Equipment_Opt_Electrical_Keyless { get; set; }

    [Display(Name = "Elec. Wireguide")]
    public bool Equipment_Opt_Electrical_Wireguide { get; set; }

    //[Display(Name = "Elec. Alarm")]
    //public bool Equipment_Opt_Electrical_Alarm { get; set; }

    //[Display(Name = "Elec. Light/Fan PKG")]
    //public bool Equipment_Opt_Electrical_Light_Fan_Pkg { get; set; }

    //[Display(Name = "Elec. Work Lights")]
    //public bool Equipment_Opt_Electrical_Work_Lights { get; set; }
    #endregion OPTION ELECTRICAL

    //END ELECTRICAL

    #region OPTION MAST
    [Display(Name = "Mast OACH")]
    public int? Equipment_Opt_Mast_Oach { get; set; }

    [Display(Name = "Elevated Height")]
    public int? Equipment_Opt_Mast_Elevated_Height { get; set; }

    #endregion OPTION MAST
}

And finally the view itself:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@model EquipmentListImportViewModel

@{
    var mymessage = "";

    if (TempData.ContainsKey("MyMessage"))
    {
        mymessage = TempData["MyMessage"] as string;
    }
}

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <form asp-controller="Equipments" asp-action="EquipmentImport" method="post" enctype="multipart/form-data">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <div class="container-fluid">
            </div><!-- /.container-fluid -->
        </section>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <h3 class="card-title">@Localizer["List of Equipment For"] @Model.Dealer_Name</h3>

                    <input asp-for="@Model.EncryptedDealer_Id" class="form-control " hidden />

                    @if (Model.EquipmentList != null)
                    {
                        <div class="row col-2">
                            @if (string.IsNullOrWhiteSpace(mymessage))
                            {
                                <div class="input-group">
                                    <button type="submit" class="btn btn-outline-info" name="submit" value="LoadEquipmentFile">
                                        @Localizer["Load Data"]
                                    </button>
                                </div>
                            }
                            else
                            {
                                <a asp-controller="Equipments" asp-action="EquipmentImport" asp-route-dealer_Id="@Model.EncryptedDealer_Id" class="btn btn-info ">
                                    @Localizer["Equip. Import"]
                                </a>
                            }
                            <br />
                        </div>
                        @if (!string.IsNullOrWhiteSpace(mymessage))
                        {
                            <h3 class="card-title text-bg-danger">@mymessage</h3>  <!-- DISPLAY ERROR MESSAGE -->
                        }
                    }
                    else
                    {
                        <div class="row col-6">
                            <div class="custom-file">
                                <input id="batchEquipmentFile" name="batchEquipmentFile" class="form-control" type="file" aria-describedby="batchEquipmentFile" accept=".xml">
                            </div>

                            <div class="input-group">
                                <button type="submit" class="btn btn-outline-info" name="submit" value="uploadEquipmentFile">
                                    @Localizer["Upload"]
                                </button>
                            </div>
                        </div>
                    }

                    @if (Model.EquipmentList != null)
                    {
                        <table id="example1" class="table table-hover table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th hidden>Dealer</th>
                                    <th>Error</th>
                                    <th>Group_Id</th>
                                    <th>Equipment_Desc</th>
                                    <th>Make_Id</th>
                                    <th>Model_Id</th>
                                    <th>Equipment_SerialNumber</th>
                                    <th>Equipment_Serie</th>
                                    <th>Equipment_Dealer_Id</th>
                                    <th>Equipment_Dealer_PKId</th>
                                    <th>Equipment_UsageHours</th>
                                    <th>Equipment_Plate</th>
                                    <th>Equipment_Notes</th>
                                    <th>Equipment_D_FirstUsed</th>
                                    <th>Equipment_Year_Manufactured</th>
                                    <th>Equipment_Photo1</th>
                                    <th>Equipment_Photo2</th>
                                    <th>Equipment_Photo3</th>
                                    <th>Equipment_Photo4</th>
                                    <th>Equipment_Photo5</th>
                                    <th>Equipment_Photo6</th>
                                    <th>Equipment_Photo7</th>
                                    <th>Equipment_Photo8</th>
                                    <th>Equipment_Photo9</th>
                                    <th>Equipment_Photo10</th>
                                    <th>Equipment_Opt_Attach_Type</th>
                                    <th>Equipment_Opt_Attach_Capacity</th>
                                    <th>Equipment_Opt_Attach_Size</th>
                                    <th>Equipment_Opt_Electrical_Volt</th>
                                    <th>Equipment_Opt_Electrical_AMP</th>
                                    <th>Equipment_Opt_Electrical_Capacity</th>
                                    <th>Equipment_Opt_Electrical_Lift_Limit</th>
                                    <th>Equipment_Opt_Electrical_Keyless</th>
                                    <th>Equipment_Opt_Electrical_Wireguide</th>

                                    <th>Equipment_Opt_Mast_Oach</th>
                                    <th>Equipment_Opt_Mast_Elevated_Height</th>

                                </tr>
                            </thead>

                            <tbody>

                                @for (int i = 0; i < Model.EquipmentList.Count; i++)
                                {
                                    <!-- LOOP MUST BE WITH FOR i and each have an input type hidden/read only otherwise, it's not returned back to the viewmodel on POST -->
                                    <tr>
                                        <td hidden><input type="text" asp-for="@Model.EquipmentList[i].Mhhr_Dealer_Key" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Error_Found" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Group_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Desc" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Make_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Model_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_SerialNumber" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Serie" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Dealer_Id" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Dealer_PKId" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_UsageHours" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Plate" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Notes" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_D_FirstUsed" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Year_Manufactured" class="form-control"></td>
                                        <td><input readonly type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo1" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo2" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo3" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo4" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo5" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo6" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo7" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo8" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo9" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Photo10" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Type" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Capacity" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Attach_Size" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Volt" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_AMP" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Capacity" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Lift_Limit" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Keyless" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Electrical_Wireguide" class="form-control"></td>

                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Mast_Oach" class="form-control"></td>
                                        <td><input type="text" asp-for="@Model.EquipmentList[i].Equipment_Opt_Mast_Elevated_Height" class="form-control"></td>

                                    </tr>
                                }

                            </tbody>

                            <tfoot>
                                <tr>
                                </tr>
                            </tfoot>
                        </table>
                    }



                </div>
                <!-- /.row -->
            </div>
            <!-- /.container-fluid -->
        </section>
        <!-- /.content -->

    </form>
</div>
<!-- /.content-wrapper -->
<!-- page script -->
@section Scripts {
    <script>
    </script>
}
Share Improve this question edited Mar 31 at 16:05 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 31 at 14:35 lbrettsinclairlbrettsinclair 351 silver badge7 bronze badges 1
  • I had another XML to load, more data but less columns . I used the exact same algorithm and code and it is working as expected on POST. Is there a limit maybe with the boostrap table ? – lbrettsinclair Commented Apr 1 at 2:11
Add a comment  | 

2 Answers 2

Reset to default 0

The issue you're facing is likely due to the maximum allowed query string length or the model binding limit in ASP.NET. When you add more properties to your class, the serialized form data exceeds the default limit.

Solution:

  1. Increase the maxQueryStringLength and maxAllowedContentLength: In your web.config file, add the following settings:

    <system.web>
        <httpRuntime maxQueryStringLength="2048" />
    </system.web>
    
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="2097152" />
            </requestFiltering>
        </security>
    </system.webServer>
    
  2. Use a different model binder:

    You can create a custom model binder that uses a different serialization mechanism, such as JSON.

    Here's an example:

    public class CustomModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var request = controllerContext.HttpContext.Request;
            var jsonString = new StreamReader(request.InputStream).ReadToEnd();
            var jsonModel = JsonConvert.DeserializeObject(jsonString, bindingContext.ModelType);
            return jsonModel;
        }
    }
    

    Then, in your controller action, use the custom model binder:

    [HttpPost]
    public ActionResult MyAction([ModelBinder(typeof(CustomModelBinder))] MyModel model)
    {
        // ...
    }
    
  3. Use a different approach: instead of using a form with many input fields, consider using a different approach, such as:

  • Using a JSON payload and sending it via AJAX.
  • Breaking down the form into smaller sections and using partial views.
  • Using a client-side framework like Angular or React to handle the form data.
  1. Check for errors - make sure to check the ModelState for errors after posting the form. This can help you identify any binding issues:
    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        if (!ModelState.IsValid)
        {
            // Handle errors
        }
        // ...
    }
    

By implementing one of these solutions, you should be able to resolve the issue and bind the form data correctly.

Since I am using MVC .Net Core 9.0.3 I added the following code in my Program.cs file.
After that, no issue loading that specific file. I probably hit somehow the Form value count limit 1024 .

services.Configure<FormOptions>(options =>
{
    options.ValueCountLimit = int.MaxValue;
});
发布评论

评论列表(0)

  1. 暂无评论