在MVC中创建自定义验证属性 [英] Creating custom validation attribute in MVC

查看:61
本文介绍了在MVC中创建自定义验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在服务器上传一个pdf文件,所以我使用

Hi, I need to upload a pdf file on server so I am using

<input type="file" name="InvoiceFile" id="FileField1" size="38" />

为此。但出于安全原因,我看到无法通过javascript访问fileupload。现在只剩下一个选项(我认为)创建自定义验证属性。所以我在模型中写了以下代码



for this. But somewhere I saw fileupload is not accessible through javascript for security reasons. Now only one option left (as I think) creating custom validation attribute. so I wrote following code in Model

public class ValidateFileAttribute : RequiredAttribute
   {
       public override bool IsValid(object value)
       {

               var file = value as string;
               if (file == null)
               {
                   return false;
               }
               else
               {
                   return true;
               }

       }
   }





和模型calss





and in model calss

[ValidateFile(ErrorMessage = "You must upload file before you proceed.")]
        public HttpPostedFileBase File { get; set; }





在视图中





in view

<input type="file" name="InvoiceFile" id="FileField1" size="38" />
                                        @Html.ValidationMessageFor(x => x.File)









in controller

 if (!ModelState.IsValid)
                {
                    return RedirectToAction("Work_orders", "Contractor");
                }
// rest of code

<当我调试代码时,我在



while I debug the code I get null in object value parameter of

public override bool IsValid(object value)

。所以它总是返回假,我无法通过验证,任何解决方案。

谢谢

of custom attribute class even after uploading file. so its always returning false and I am unable to pass validations, any solution.
Thanks

推荐答案

你好Imadoddin,



我认为你可以找到解决方案这里 [ ^ ]。

此外,您可以参考此链接 [ ^ ]和这一个 [ ^ ]。

你可以用Javasceript来做。



希望这对你有所帮助。



问候,

RK
Hi Imadoddin,

I think you can find solution here[^].
Moreover you can refer this link [^]and this one[^].
You can use Javasceript to do it.

Hope this helps you a bit.

Regards,
RK


这篇关于在MVC中创建自定义验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆