当FILE类型为

时间:2018-05-07 00:25:36

标签: c# asp.net unobtrusive-validation

我有一个控制器,用户选择一个文件,其中包含要在系统中加载的数据,但我需要验证文件尚未加载,因此我尝试创建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; }
}

以及包含jquery.validatejquery.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类型

的问题

0 个答案:

没有答案