无法使用 SetModelValue 修改 ModelState [英] Cannot modify ModelState using SetModelValue

查看:30
本文介绍了无法使用 SetModelValue 修改 ModelState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 MVC/EF Web 应用程序.在其中一种表格中,我编辑了一个模型.该模型有一个图像字段 (public byte[] BioPhoto)

当我将图像上传到该字段并保存数据时,ModelState.IsValidfalse,因为 BioPhoto 属性为 null 在 ModelState 中.请注意,模型中的 BioPhoto 加载了图像数据.

我尝试使用下面的代码将图片注入到 ModelState 中,但 ModelState.IsValid 仍然是 false

public ActionResult Edit([Bind(Include = "BusinessId,Name,About,Phone,TollFree,FAX,Email,Bio,BioPhoto")] 商业业务){if (System.IO.File.Exists("image.jpg")){business.BioPhoto = System.IO.File.ReadAllBytes("image.jpg");ModelState.SetModelValue("BioPhoto",new ValueProviderResult(business.BioPhoto, "", System.Globalization.CultureInfo.InvariantCulture));}如果(模型状态.IsValid){db.Entry(business).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("索引");}返回视图(业务);}

我做错了什么.这个问题有没有更好的解决方案?

我在 SO 中阅读了几个答案,但不知道如何解决我的问题.

这是我的模型

公共类业务{公共 int BusinessId { 获取;放;}[必需的][字符串长度(100)]公共字符串名称 { 获取;放;}[必需的]公共地址地址{获取;放;}[必需的][字符串长度(20)]公共字符串电话{得到;放;}[字符串长度(20)]公共字符串 TollFree { 获取;放;}[字符串长度(20)]公共字符串传真{获取;放;}[必需的][字符串长度(50)]公共字符串电子邮件{获取;放;}[必需的][字符串长度(100)]公共字符串网站{获取;放;}[必需的]公共字符串关于{获取;放;}[必需的]公共字符串生物{得到;放;}[必需的]公共字节 [] 生物照片 { 获取;放;}}

我的观点

@Html.LabelFor(model => model.BioPhoto, "BIO 照片 (最佳尺寸: 350 x 450)", htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10"><form enctype="multipart/form-data"><div class="form-group" style="width:400px"><input id="BioPhoto" type="file" multiple class="file" data-overwrite-initial="false"/>

</表单>@Html.ValidationMessageFor(model => model.BioPhoto, "", new { @class = "text-danger" })

解决方案

就像我说的,问题是表单没有将 BioPhoto 发布到控制器 - 很可能.您可以使用 Chrome 查看 http 请求正文中的内容.

如果您想在控制器未收到图像的情况下添加图像,请尝试此操作.

尝试仅删除与图像属性相关的错误:

ModelState["BioPhoto"].Errors.Clear();

然后添加图片:

business.BioPhoto = System.IO.File.ReadAllBytes("image.jpg");

然后更新模型:

UpdateModel(business);

现在如果你调用ModelState.IsValid,它会考虑BioPhoto的设置并重新评估IsValid.>

我建议打电话

ModelState.SetModelValue("BioPhoto", new ValueProviderResult(business.BioPhoto, "", System.Globalization.CultureInfo.InvariantCulture));

实际将值推送到 ModelState.Values.但这不是必需的.

I'm working on a MVC/EF Web Application. In one of the forms I edit a model. The model has an image field (public byte[] BioPhoto)

When I upload an image to that field and save data, ModelState.IsValid is false, because BioPhoto property is null in ModelState. Note that the BioPhoto in model is loaded with image data.

I tried to inject the picture to ModelState using below code but still ModelState.IsValid is false

public ActionResult Edit([Bind(Include = "BusinessId,Name,About,Phone,TollFree,FAX,Email,Bio,BioPhoto")] Business business)
{
    if (System.IO.File.Exists("image.jpg"))
    {
        business.BioPhoto = System.IO.File.ReadAllBytes("image.jpg");
        ModelState.SetModelValue("BioPhoto", 
                   new ValueProviderResult(business.BioPhoto, "", System.Globalization.CultureInfo.InvariantCulture));
    }

    if (ModelState.IsValid)
    {
        db.Entry(business).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(business);
}

What am I doing wrong. Is there any better solution for this issue?

I read couple of answer in SO but could not figure out how to solve my case.

This is my model

public class Business
{
    public int BusinessId { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Required]
    public Address address { get; set; }

    [Required]
    [StringLength(20)]
    public string Phone { get; set; }

    [StringLength(20)]
    public string TollFree { get; set; }

    [StringLength(20)]
    public string FAX { get; set; }

    [Required]
    [StringLength(50)]
    public string Email { get; set; }

    [Required]
    [StringLength(100)]
    public string WebSite { get; set; }

    [Required]
    public string About { get; set; }

    [Required]
    public string Bio { get; set; }

    [Required]
    public byte[] BioPhoto { get; set; }
}

My View

<div class="form-group">
    @Html.LabelFor(model => model.BioPhoto, "BIO Photo (Best Size: 350 x 450)", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <form enctype="multipart/form-data">
            <div class="form-group" style="width:400px">
                <input id="BioPhoto" type="file" multiple class="file" data-overwrite-initial="false" />
            </div>
        </form>
        @Html.ValidationMessageFor(model => model.BioPhoto, "", new { @class = "text-danger" })
    </div>
</div>

解决方案

Like I said the issue is the form is not posting the BioPhoto to the controller-most likely. You can use Chrome to see what is in the body of the http request.

If you want to add the image even if the controller is not receiving it, then try this.

Try removing only the error related to the image property:

ModelState["BioPhoto"].Errors.Clear();

Then add the image:

business.BioPhoto = System.IO.File.ReadAllBytes("image.jpg");

Then update the model:

UpdateModel(business);

Now if you call ModelState.IsValid, it will take the setting of BioPhoto into consideration and re-evaluate the IsValid.

EDIT:

I suggest to call

ModelState.SetModelValue("BioPhoto", new ValueProviderResult(business.BioPhoto, "", System.Globalization.CultureInfo.InvariantCulture));

to actually push the value to ModelState.Values. this is not neccessary though.

这篇关于无法使用 SetModelValue 修改 ModelState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆