首页 > 解决方案 > 当是 FILE 类型时,远程验证不接收字段值

问题描述

我有一个控制器,用户在其中选择一个要在系统中加载数据的文件,但我需要验证该文件之前尚未加载,所以我尝试创建一个Remote验证

我创建一个类:

public class FileUpload
{
    [Display(Name = "Archivo")]
    [Required(ErrorMessage = "Debe seleccionar un archivo.") ]
    [Remote("BackupFileExist", "ImportJobs", ErrorMessage = "El archivo ya fue cargado.")]
    public HttpPostedFileBase File { get; set; }

    [Display(Name = "Test")]
    [Required(ErrorMessage = "Debe seleccionar un archivo.")]
    [Remote("BackupTestExist", "ImportJobs", ErrorMessage = "El archivo ya fue cargado.")]
    public string Test { get; set; }
}

以及带有 and 的强类型jquery.validate视图jquery.validate.unobtrusive

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">
                @Html.TextBoxFor(x => x.File, new { type = "file" })
                @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
            </div>
        </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Test, htmlAttributes: new { @class = "control-label col-md-2" })

        <div class="col-md-10">
            @Html.TextBoxFor(x => x.Test, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.ValidationMessageFor(model => model.Test, "", new { @class = "text-danger" })
        </div>
    </div>

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

@section scripts {
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
}

然后我的控制器:

public class ImportJobsController : Controller
{
    public JsonResult BackupFileExist(HttpPostedFileBase File)
    {
        return Json(!db.ImportJobs.Any(f => f.FileName == File.FileName), 
                    JsonRequestBehavior.AllowGet);
    }

    public JsonResult BackupTestExist(string Test)
    {
        return Json(!db.ImportJobs.Any(f => f.FileName == Test), JsonRequestBehavior.AllowGet);
    }
} 

我的问题是BackupFileExist函数被调用但File变量为空

编辑:发布问题后,我决定添加一个Test字符串类型的字段。该领域按预期工作。所以看起来是File类型的问题

标签: c#asp.netunobtrusive-validation

解决方案


推荐阅读