我是新的ASP.Net MVC 4.我有一個文本框和一個按鈕。點擊按鈕後,我想在文本框爲空時顯示錯誤消息。我想顯示錯誤消息,當文本框爲空mvc4
任何人都可以幫助我。 我的賬戶類是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;
namespace WebApplication6.Models
{
public class Account
{
[Required(ErrorMessage = "Please enter your name {0}")]
[StringLength(5)]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your Family {0}")]
public string Family { get; set; }
}
}
我的佈局頁:
<!DOCTYPE html>
<link href="~/Content/CSS/site.css" rel="stylesheet" />
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<header>
<div class="header">
<img src="~/Content/Images/Logo.jpg" style="position:center; border-top-color:red;" />
</div>
</header>
<div>
<h1 class="header">Wellcome to company's project</h1>
</div>
<div>
@RenderBody()
</div>
<footer>
@Html.Partial("_Footer")
</footer>
</body
> 我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class LoginController : Controller
{
//
// GET: /Login/
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult LoginResult()
{
Account Oaccount = new Account();
Oaccount.Name = Request.Form["name"];
Oaccount.Family = Request.Form["family"];
/*if (Oaccount.Name=="" || Oaccount.Family=="")
{
return Content("<script language='javascript' type='text/javascript'>alert('You must enter both fields');</script>");
return RedirectToAction("Index");
}
else {*/
string Fullname=string.Format("{0} {1}", Oaccount.Name,Oaccount.Family);
ViewBag.Message = Fullname;
return View("Result");
}
我的索引視圖是:
@model WebApplication6.Models.Account
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/Layouts/_LayoutPage.cshtml";
}
@using (Html.BeginForm(actionName: "LoginResult", controllerName: "Login"))
{
<fieldset >
<legend>Login</legend>
<p class="textbox">
Name: @Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model=>model.Name)
</p>
<p >
Family: @Html.TextBoxFor(model => model.Family)
@Html.ValidationMessageFor(model=>model.Family)
</p>
<p class="button">
<input type="submit" value="Login" />
</p>
</fieldset>
}
}
}
我的結果的看法是:
@using WebApplication6.Models
@model WebApplication6.Models.Account
@{
ViewBag.Title = "Result";
Layout = "~/Views/Shared/Layouts/_LayoutPage.cshtml";
}
<h2>Result</h2>
<fieldset>
<legend>Login Result</legend>
<p>
Wellcome
@ViewBag.Message
</p>
</fieldset>>
你如何渲染該文本框?您是否使用HtmlHelper擴展? – cezarypiatek
我使用html.beginform和html.textboxfor –
是否有任何理由你不使用客戶端驗證(所以你開箱即可得到客戶端和服務器端驗證)?其他方面,你將需要JavaScript來處理按鈕'.click()'事件,檢查值並顯示一條消息。 –