Reputation: 449
I have a form for upload images in asp.net mvc 5 .
Every thing is OK , but there is a problem with Validation Error Message
. If I select image in upload control or not , My webApplication always give me alert message error happened , your data is not valid
.
but when I delete [Required(ErrorMessage = "select image plz")]
from MainGoodMetaData.cs
it works fine !
Could any one help me please ? Thanks a lot
MainGoodMetaData.cs
[Required(ErrorMessage = "select image plz")]
[DisplayName("good image")]
[Display(Name = "good image")]
[DataType(System.ComponentModel.DataAnnotations.DataType.ImageUrl)]
public string GoodImage { get; set; }
AddMainGood.cshtml
<div class="form-group">
<div class="col-md-10">
@Html.Upload("UploadImage")
@Html.ValidationMessageFor(model => model.GoodImage)
</div>
@Html.LabelFor(model => model.GoodImage, new { @class = "control-label col-md-2" })
</div>
Admin controller
[HttpPost]
public ActionResult AddMainGood(MainGood maingood, HttpPostedFileBase UploadImage)
{
MainGoodRepositories blMainGood = new MainGoodRepositories();
string path2 = "";
var fileName2 = "";
var rondom2 = "";
if (UploadImage != null)
{
fileName2 = Path.GetFileName(UploadImage.FileName);
string pic = System.IO.Path.GetFileName(UploadImage.FileName);
rondom2= Guid.NewGuid() + fileName2;
path2 = System.IO.Path.Combine(
Server.MapPath("~/Images/MainGoods"), rondom2);
maingood.GoodImage = rondom2;
}
if (ModelState.IsValid)
{
UploadImage.SaveAs(path2);
maingood.GoodImage = rondom2;
if (blMainGood.Add(maingood))
{
return JavaScript("alert('added');");
}
else
{
return JavaScript("alert('didn't add');");
}
}
else
{
return JavaScript("alert('error happened , your data is not valid');");
}
}
UploadHelper.cs
public static class UploadHelper
{
public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null)
{
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
public static MvcHtmlString UploadFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
</div>
Upvotes: 0
Views: 1917
Reputation: 10824
There are a lot of ways for validating a file input both server side and client side, it depends on the situation you're working on. for example, if you want a complex validation on the server side you can create a custom validation attribute. But if you want just a simple required file input using client side validation you should change your model:
[Required(ErrorMessage = "Select a file")]
public HttpPostedFileBase GoodImage { get; set; }
As you can see, I the GoodImage
property to HttpPostedFileBase
, then inside your view we just simply add required validation manually:
<div class="form-group">
<div class="col-md-10">
<input type="file" data-val="true" data-val-required="please select a file" name="GoodImage" />
@Html.ValidationMessage("file")
</div>
@Html.LabelFor(model => model.GoodImage, new {@class = "control-label col-md-2"})
</div>
<input type="submit" value="Send"/>
And your action method:
[HttpPost]
public ActionResult AddMainGood(MainGood model)
{
if (!ModelState.IsValid)
{
return View(model);
}
string path2 = "";
var fileName2 = "";
var rondom2 = "";
fileName2 = Path.GetFileName(model.GoodImage.FileName);
string pic = System.IO.Path.GetFileName(model.GoodImage.FileName);
rondom2 = Guid.NewGuid() + fileName2;
path2 = System.IO.Path.Combine(
Server.MapPath("~/Images/MainGoods"), rondom2);
// other code
}
Upvotes: 3