【问题标题】:Why I get Null value from view to controller only for one column?为什么我只为一列从视图到控制器获取 Null 值?
【发布时间】:2022-09-23 15:01:23
【问题描述】:

我在 ASP.NET Core 6 MVC 中练习 CRUD 操作。我尝试上传单张图片的方法。图像是在创建方法上上传的。但是当我尝试使用编辑方法而不改变图像时。它在 Edit post 方法上给出空值。

我将图像列作为字符串并仅保存由 AJAX url 通过 javascript 生成的随机名称。准时创建,图像上传+ javascript运行并获取随机名称+保存在数据库中。但是当我尝试编辑方法时,没有上传新图像,它保存为 Null(图像显示在编辑页面上。)

控制器Edit post 方法的代码:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, CustomerMaster customerMaster, IFormCollection formData)
{
    if (ModelState.IsValid)
    {
        try
        {
            if (!_context.CustomerMasters.Any(x => x.MobileNo == customerMaster.MobileNo && x.CustomerId != id))
            {
                CustomerMaster customer = await _context.CustomerMasters.FindAsync(id);
                customer.CustomerName = customerMaster.CustomerName;
                customer.MobileNo = customerMaster.MobileNo;
                customer.Email = customerMaster.Email;
                customer.Address = customerMaster.Address;
                customer.Image = customerMaster.Image;
                customer.WhenEntered = DateTime.UtcNow;

                _context.Update(customer);
                await _context.SaveChangesAsync();

                return RedirectToAction(nameof(Index));
            }
            else
            {
                ModelState.AddModelError(\"\", \"Name with same mobile no. already exists.\");
            }
        }

        return RedirectToAction(nameof(Index));
    }

    return View(customerMaster);
}

这是我的edit.cshtml

\'\'\'\'

@model Customer_Crud_Demo.Models.CustomerMaster

@using Customer_Crud_Demo.Common

@{
    ViewData[\"Title\"] = \"Edit\";
    string imagePath = string.IsNullOrEmpty(Model.Image) ? \"https://via.placeholder.com/200x200\" : Config.customerImagePath + Model.Image.Replace(\".\", \".\");
}

在配置中

customerImagePath = \"/Content/MultiCustomerImg/\"

表单内的edit.cshtml

<form asp-action=\"Edit\" enctype=\"multipart/form-data\">
    <div asp-validation-summary=\"ModelOnly\" class=\"text-danger\"></div>
    <input type=\"hidden\" asp-for=\"CustomerId\" />
        <label asp-for=\"Image\" class=\"control-label\"></label>

        <table>
            <tr>
                <td>
                    <input type=\"file\" asp-for=\"Image\" id=\"fuCustomerImage\" class=\"fu form-control\" accept=\".jpg,.jpeg,.png\" />
                </td>
                <td>
  <input type=\"button\" value=\"Upload\" id=\"btnUploadImage\" class=\"btn btn-primary\" data-URL=\"CustomerMaster/UploadFile\" data-path=\"/Content/CustomerImages\" />
                </td>
            </tr>
            <tr>
                <td>
                    <span asp-validation-for=\"Image\" class=\"text-danger\"></span>
                </td>
            </tr>
            <tr>
                <td class=\"error\" colspan=\"2\">
                    Please upload image of 200 X 200 and size less than 150KB.
                </td>
            </tr>
        </table>
                        
        <div class=\"singleImage\">
            <img src=\"@imagePath\" alt=\"Alternate Text\" id=\"ImgUploadedImage\" height=\"200\" width=\"200\" />
            @Html.HiddenFor(model => model.Image, new { id = \"image\" })
        </div>
</form>

我的错误是什么?请纠正我。

    标签: c# asp.net-core .net-core file-upload image-upload


    【解决方案1】:

    在您的Edit.cshtml 中,您有两个具有相同名称的input 标签:

    1.

    <input type="file" asp-for="Image" id="fuCustomerImage" class="fu form-control" accept=".jpg,.jpeg,.png" />
    

    2.

    @Html.HiddenFor(model => model.Image, new { id = "image" })
    

    它们都会在 HTML 中生成类似&lt;input Name="Image" ..../&gt; 的代码。

    ModelBinding 只会绑定第一个 Input 的值,这就是为什么即使你不更改 Image 中的任何内容也会得到 null 的原因。你可以参考这段代码:

    编辑.cshtml

    <input type="file" Name="file" id="fuCustomerImage" class="fu form-control" accept=".jpg,.jpeg,.png" />
    

    编辑方法

    [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, CustomerMaster customerMaster, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (!_context.CustomerMasters.Any(x => x.MobileNo == customerMaster.MobileNo && x.CustomerId != id))
                    {
                        CustomerMaster customer = await _context.CustomerMasters.FindAsync(id);
                            customer.CustomerName = customerMaster.CustomerName;
                            customer.MobileNo = customerMaster.MobileNo;
                            customer.Email = customerMaster.Email;
                            customer.Address = customerMaster.Address;
    
                        if (file != null)
                        {
                            //I don't how you save file as string in database, Here i just save file name as an example
                            customer.Image = file.FileName
                        }
                        else
                        {
                            customer.Image = customerMaster.Image;
                        }
                            
                            customer.WhenEntered = DateTime.UtcNow;
    
                            _context.Update(customer);
                            await _context.SaveChangesAsync();
                        
                    }
                    else
                    {
                        ModelState.AddModelError("", "Name with same mobile no. already exists.");
                    }
                }
    
    
            return RedirectToAction(nameof(Index));
            }
    
            return View(customerMaster);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多