【问题标题】:Cannot make Byte a Required Field不能使字节成为必填字段
【发布时间】:2018-04-30 06:33:41
【问题描述】:

有一个我想上传图片的应用。我为此使用字节数组。

图像是必需的,但是当我将该注释放在变量上并尝试创建图像时,它会在应该有图像时给我错误消息。它还返回模型无效。

当我删除必需项时,它可以工作,但也可以设置为 null,这是我不想要的。

关于 Stack Overflow 的话题似乎并不多。

这是我的模型

[Key]
public int InvoiceId { get; set; }

[Required(ErrorMessage = "Company is required")]
public string Company { get; set; }

[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }

[Required(ErrorMessage = "Amount is required")]
public decimal Amount { get; set; }

[Required(ErrorMessage = "Picture of Invoice Required")]
public byte[] PictureOfInvoice { get; set; }

还有我的控制器:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create([Bind(Include = "InvoiceId,Company,Description,Amount,PictureOfInvoice,DateReceived,ChurchId")] Invoice invoice,HttpPostedFileBase File)
{
    if (ModelState.IsValid)
    {
        if (File != null && File.ContentLength > 0)
        {                   
            invoice.PictureOfInvoice = new byte[File.ContentLength];
            File.InputStream.Read(invoice.PictureOfInvoice, 0, File.ContentLength);

        }
        else
        {
            TempData["Error"] = "Upload an Image";
        }

        db.Invoices.Add(invoice);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
    return View(invoice);
}

我的观点,以防万一它在那里:

<h2>Add New Invoice</h2>

@if (TempData["Error"] != null)
{
    <div style="color:red">@TempData["Error"]</div>
}

@using (Html.BeginForm("Create", "Invoices", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Company, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Company, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
                @Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Amount,new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
                @Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateReceived, "DateRecieved", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.DateReceived, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
                @Html.ValidationMessageFor(model => model.DateReceived, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PictureOfInvoice, "Picture of Invoice", htmlAttributes: new { @class = "control-label col-md-2"})
            <div class="col-md-10">
                <input type="file" name="File" id="File" style="width: 50%;" />
                @Html.ValidationMessageFor(model => model.PictureOfInvoice, "", new { @class = "text-danger" })
                <output id="list"></output>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ChurchId, "Church Name", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ChurchId", null, htmlAttributes: new { @class = "form-control", style = "width:20em;" })
                @Html.ValidationMessageFor(model => model.ChurchId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    <u>
        @Html.ActionLink("Back to List", "Index")
    </u>
</div>


<script src="~/Scripts/jquery.datetimepicker.js"></script>

<script>
    $('#DateReceived').datetimepicker({
        format: 'd/m/Y',
        weeks: true,
        disableWeekDays: [0, 1, 3, 4, 5, 6],
        timepicker: false,
        inline: false
    });

    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList and render image files as thumbnails.
        for (var i = 0, f; f = files[i]; i++) {

            // Only process image files.
            if (!f.type.match('image.*')) {
                continue;
            }

            var reader = new FileReader();

            // Closure to capture the file information.
            reader.onload = (function (theFile) {
                return function (e) {
                    // Render thumbnail.
                    var span = document.createElement('span');
                    span.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/>'
                    ].join('');
                    document.getElementById('list').insertBefore(span, null);
                };
            })(f);

            // Read in the image file as a data URL.
            reader.readAsDataURL(f);
        }
    }

    document.getElementById('File').addEventListener('change', handleFileSelect, false);
</script>

【问题讨论】:

  • 没有属性会改变您可以将array 属性设置为null 的事实。也许MinLength 会更好地为您的验证工作? stackoverflow.com/questions/13361500/…
  • @juharr 没有为我做任何事情,甚至没有提供错误消息。我太绝望了,我愿意为此放弃我所有的代表大声笑
  • 在您看来,PictureOfInvoice 有一个 标签PictureOfInvoice 有一个验证消息,但我不知道如何您希望 &lt;input type="file"&gt;PictureOfInvoice 绑定到该属性?
  • @Damien_The_Unbeliever 我明白你的意思。但是当我没有所需的部分时它确实有效
  • 您的编辑数据,因此请始终使用视图模型 - 它将包含一个属性 HttpPostedFileBase 将文件绑定到,但它不包含 byte[] 属性(请参阅 What is ViewModel in MVC?

标签: c# asp.net-mvc


【解决方案1】:

这里的关注点混合会导致问题。您似乎正在尝试将实体用作视图的模型,并使其同时满足 UI 验证和持久性验证。

分离两个关注点。

创建特定于所需视图行为的视图模型。 该模型还应包含IEnumerable&lt;SelectListItem&gt; ChurchList 属性以填充下拉列表。

public class CreateInvoiceViewModel {

    [Required(ErrorMessage = "Company is required")]
    public string Company { get; set; }

    [Required(ErrorMessage = "Description is required")]
    public string Description { get; set; }

    [Required(ErrorMessage = "Amount is required")]
    public decimal Amount { get; set; }

    [Required(ErrorMessage = "Picture of Invoice Required")]
    public HttpPostedFileBase File { get; set; }

    public int ChurchId { get; set; }

    public IEnumerable<SelectListItem> ChurchList { get; set; }

    //...other properties
}

并将其设置为视图的模型

@model CreateInvoiceViewModel

如果创建新发票,则尚未分配 ID。这意味着在发布您当前拥有的模型时,模型状态不能有效,因为InvoiceId 标记为Required 未提供。

上传的文件(发票图片)也应该包含在视图模型中,并且应该使用@Html.TextBoxFor(m =&gt; m.File, new { type = "file" }) 来获得客户端验证。模型绑定器将根据是否提供了匹配的输入来设置该属性。

<div class="form-group">
    @Html.LabelFor(model => model.File, "Picture of Invoice", htmlAttributes: new { @class = "control-label col-md-2"})
    <div class="col-md-10">            
        @Html.TextBoxFor(model => model.File, new { type = "file", style = "width: 50%;"})
        @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
        <output id="list"></output>
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ChurchId, "Church Name", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.ChurchId, (IEnumerable<SelectListItem>)@Model.ChurchList, htmlAttributes: new { @class = "form-control", style = "width:20em;" })
        @Html.ValidationMessageFor(model => model.ChurchId, "", new { @class = "text-danger" })
    </div>
</div>

所以现在在控制器端,[Bind] 应该被删除,因为在使用视图模型时不需要它。

[HttpGet]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create() {
    var model = new CreateInvoiceViewModel {
        //set default property values as needed
    };

    model.ChurchList = new SelectList(db.Churches, "ChurchId", "Name");

    //...

    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create(CreateInvoiceViewModel model) {
    if (ModelState.IsValid) {
        var file = model.File;
        //copy properties over to entity
        var invoice = new Invoice {
            Company = model.Company,
            Description = model.Description,
            Amount = model.Amount,
            DateReceived = model.DateReceived,
            ChurchId = model.ChurchId,
            //create array for file contents
            PictureOfInvoice = new byte[file.ContentLength]
        };
        //populate byte array
        file.InputStream.Read(invoice.PictureOfInvoice, 0, file.ContentLength);

        db.Invoices.Add(invoice);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    //if we get this far model state is invalid.
    //return view with validation errors.
    model.ChurchList = new SelectList(db.Churches, "ChurchId", "Name", model.ChurchId);
    return View(model);
}

如果模型要求无效,模型状态将提供必要的反馈。无需使用临时数据和文件检查。

【讨论】:

  • 一些小的更正 - 应该是 @Html.TextBoxFor(m =&gt; m.File, new { type = "file" }) 以便您获得客户端验证。 [FromBody] 不适用(仅适用于 web-api)并且应该删除 [Bind] - 使用视图模型时从不需要它。
  • 模型还应该包含int SelectedChurchIEnumerable&gt;SelectListItem&gt; ChurchList,应该是model.ChurchList = new SelectList(db.Churches, "ChurchId", "Name");
  • @StephenMuecke 进行更新。感谢您的反馈。
【解决方案2】:

您没有使用数据绑定在模型中填充PictureOfInvoice - 您是在控制器的方法中执行此操作。但是您只是在确认模型有效之后才执行该步骤,而按照这种逻辑是不可能的。

我认为您可以尝试只切换前几位:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create(
[Bind(Include = "InvoiceId,Company,Description,Amount,DateReceived,ChurchId")]
     Invoice invoice,
     HttpPostedFileBase File)
{
    if (invoice!=null && File != null && File.ContentLength > 0)
    {                   
        invoice.PictureOfInvoice = new byte[File.ContentLength];
        File.InputStream.Read(invoice.PictureOfInvoice, 0, File.ContentLength);
    }
    if (ModelState.IsValid)
    {
        //Proceed

如果这仍然没有让模型通过验证,那么您可能必须像以前在 else 中那样继续应用错误

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多