【发布时间】:2018-04-15 00:18:18
【问题描述】:
为什么我的代码没有抛出错误?它将 ModelState.IsValid 呈现为 false,这没关系,但当我将 Story 文本框留空时不会引发错误。
它浪费了我一整天,但仍然无法弄清楚发生了什么?
帮帮我。
我不认为它包含任何错误,但它仍然不会抛出我在模型中定义的所需错误。
查看:
<div class="form-group">
@Html.LabelFor(model => model.Story, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Story, new { htmlAttributes = new { @class = "form-control white" } })
@Html.ValidationMessageFor(model => model.Story, "", new { @class = "text-danger" })
</div>
</div>
型号:
namespace HimHer.Models
{
public class Stories
{
public int ID { get; set; }
public string Image { get; set; }
[Required(AllowEmptyStrings=false, ErrorMessage="Story required")]
public string Story { get; set; }
public int HiddenID { get; set; }
}
}
控制器:
[HttpPost]
public ActionResult AddStories(Stories st, HttpPostedFileBase files)
{
try
{
if (ModelState.IsValid)
{
if (files != null)
{
string filePath = Path.Combine(Server.MapPath("~/UploadedFiles/"), Path.GetFileName(files.FileName));
files.SaveAs(filePath);
}
st.Image = Path.GetFileName(files.FileName);
listofStories.Clear();
listofStories = bo.GetAllImages();
if (bo.insertImages(st))
{
ViewBag.Data = "Added";
ViewBag.Grid = listofStories;
ViewBag.Style = "display:none";
ViewBag.StyleAdd = "";
}
else
{
}
}
}
catch (Exception ex)
{
ViewBag.Data = ex.Message;
}
return RedirectToAction("AddStories", "Stories");
}
【问题讨论】:
-
“代码抛出错误”是什么意思?如果您说 Model.IsValid 为假,那么这是预期的行为。在您的操作中,您检查它是否为假 - 在这里没有任何问题。
-
我相信你遇到了和这里一样的问题:stackoverflow.com/questions/17923622/…
-
您的意思是提交表单时没有显示错误吗? - 在这种情况下,您没有正确实施客户端验证
标签: c# asp.net asp.net-mvc asp.net-mvc-4 model-view-controller