【问题标题】:Null values from viewmodel when trying to upload file with data尝试上传带有数据的文件时来自视图模型的空值
【发布时间】:2023-03-15 01:37:01
【问题描述】:

我正在尝试创建一个视图,让用户可以上传 Office 文件以及包含 URL、类型等的类。我目前正在使用此视图模型:

public class ServiceFileUploadViewModel
{
    public FileUpload File { get; set; }
    public IList<Service> AvalibleServices { get; set; }
    public IList<Service> SelectedServices { get; set; }
    public PostedServices PostedServices { get; set; }
    public HttpPostedFileBase FileUpload { get; set; }

}
public class PostedServices
{
    public int[] ServicesIds { get; set; }
}

我正在使用一个名为“CheckBoxListFor”的扩展程序,它创建了一个复选框列表,它将文件链接到特定的服务。

这是我对表单的看法:

@model ServiceFileUploadViewModel


@using (Html.BeginForm("_Upload", "ServiceCatalog", FormMethod.Post, new { enctype = "multipart/form-data" }))

{
<div>
    <input type="file" name="file" />
</div>

<div>
    Dokumenttyp
</div>
<div>
    @Html.EditorFor(m => m.File.DocumentType)
</div>

<div>
    @Html.CheckBoxListFor(m => m.PostedServices.ServicesIds,
                        m => m.AvalibleServices,
                        entity => entity.Id,
                        entity => entity.Name,
                        m => m.SelectedServices,
                        Position.Vertical)
</div>

<div>
    <label>Visningsalternativ</label>
</div>
<div>
    @Html.RadioButtonFor(m => m.File.IsPrivate, "true", true) Interninformation
</div>
<div>
    @Html.RadioButtonFor(m => m.File.IsPrivate, "false", false) Kundinformation
</div>

<input type="submit" value="Ladda upp" />
}

我的问题是,当我在 Controller 的 _Upload Action 中设置断点时,所有值(文件、FileUpload-Class)都为空,但包含在 Checkboxlist 中选择的服务的“PostedServices”数组除外。

我一直试图解决这个问题,但没有成功。关于为什么我的表单没有正确映射到我的视图模型的任何想法?

【问题讨论】:

    标签: c# asp.net-mvc razor model-binding


    【解决方案1】:

    您的HttpPostedFileBase FileUpload 属性将为null,因为您已将输入命名为“文件”。应该是

    <input type="file" name="FileUpload" />.
    

    这也意味着FileUpload File 将在回发时为空,因为您尝试将上传文件的值绑定到 typeof FileUpload(这当然失败 - 因此它是 null)。

    注意:您尚未发布您的 FileUpload 课程,因此无法确定是否存在其他问题。

    还请注意,您应该从@Html.RadioButtonFor() 中删除第三个参数。您使用强类型帮助器,这意味着所选按钮将基于 IsPrivate 的值

    【讨论】:

    • 就是这样!非常感谢您快速准确的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2020-11-11
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多