mvc 验证html,在mvc中验证纯HTML表单

是的,你可以添加ModelState.AddModelError但在你看来,如果你想显示此消息,你应该使用一些HTML佣工如Html.ValidationSummary或Html.ValidationMessage的。

例如,在您的视图:

@Html.ValidationMessage("file")

,并在你的控制器动作:

ModelState.AddModelError("file", "some error message");

显然,这是更好的使用视图模型,这些佣工的强类型的等价物以及使用帮助者生成你的标记,而不是像你的情况那样对它进行硬编码。

你知道,事情就是:

public class MyViewModel

{

[Required(ErrorMessage = "Please select a file first")]

public HttpPostedFileBase File { get; set; }

[Required(ErrorMessage = "Please enter a name")]

public string Title { get; set; }

public string Description { get; set; }

}

,并在您看来的东西,如:

@model MyViewModel

...

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

{

@Html.AntiForgeryToken()

Open

@Html.TextBoxFor(x => x.File, new {

type = "file",

style = "opacity:0",

οnchange="document.getElementById('title').value = this.value.substring(this.value.lastIndexOf('\\') +1);"

})

@Html.ValidationMessageFor(x => x.File)

@Html.EditorFor(x => x.Title)

@Html.ValidationMessageFor(x => x.Title)

@Html.TextAreaFor(x => x.Description)

}

,并在你的控制器动作:

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Upload(MyViewModel model)

{

if (!ModelState.IsValid)

{

return View(model);

}

try

{

Image.FromStream(model.File.InputStream);

}

catch (ArgumentException)

{

ModelState.AddModelError("File", "The file you are trying to upload is not a valid image file.");

}

// At this stage you know that the model is valid =>

// you could do something with those model.Title and model.Description properties

return RedirectToAction("Success");

}

通过你可能采取的方式看看following answer of mine从你的控制器动作中删除更多管道/验证代码不属于那里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值