我是MVC的新手,所以我并不完全确定我将模型绑定到控制器并按原样查看。发生错误后,我试图弹出一条消息。在这种情况下,单击提交按钮后会发生错误。
观点......
@if (ViewBag.Message != null)
{
<script>
$(document).ready(function () {
alert('@ViewBag.Message');
});
</script>
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Guru Dental: Request Demo</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,400">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel="stylesheet" href="~/Content/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="~/Content/assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="~/Content/assets/css/animate.css">
<link rel="stylesheet" href="~/Content/assets/css/magnific-popup.css">
<link rel="stylesheet" href="~/Content/assets/flexslider/flexslider.css">
<link rel="stylesheet" href="~/Content/assets/css/form-elements.css">
<link rel="stylesheet" href="~/Content/assets/css/style.css">
<link rel="stylesheet" href="~/Content/assets/css/media-queries.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="~/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="~/images/favicon.ico" type="image/x-icon">
</head>
<body>
<!-- Top menu -->
<nav class="navbar" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#top-navbar-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<br>
<a href="http://www.gurudental.com/"><img class="logo-size" src="~/images/guru-dental-slogan.png" alt=""></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="top-navbar-1">
<ul class="nav navbar-nav navbar-right">
<li><a href='@Url.Action("Index", "Home")'><br><br>Home</a></li>
<li>
<a href='@Url.Action("Contact", "Home")'><br><br>Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Title -->
<div class="page-title-container">
<div class="container">
<div class="row">
<div class="col-sm-12 wow fadeIn">
<h1>Demo Request</h1>
</div>
</div>
</div>
</div>
<!-- Contact Us -->
<div class="contact-us-container">
<div class="container">
<div class="row">
<div class="col-sm-7 contact-form wow fadeInLeft">
@using (Html.BeginForm("DemoSubmit", "CRM", FormMethod.Post))
{
<h2>Rep Details</h2>
<div class="form-group">
<label for="contact-firstname">HSD Rep Code</label>
<input type="text" name="hsdrepcode" placeholder="Enter your HSD Rep code..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep First Name</label>
<input type="text" name="hsfirstname" placeholder="Enter your Rep first name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep Last Name</label>
<input type="text" name="hslastname" placeholder="Enter your Rep last name..." class="contact-name" id="contact-name">
</div>
<h2>Doctor Details</h2>
<div class="form-group">
<label for="contact-currentlocation">Doctor's First Name</label>
<input type="text" name="firstname" placeholder="Enter your doctor's first name.." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Last Name</label>
<input type="text" name="lastname" placeholder="Enter your doctor's last name..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Phone Number</label>
<input type="text" name="phonenumber" placeholder="Enter your doctor's phone number..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's E-mail</label>
<input type="text" name="emailaddress" placeholder="Enter your doctor's e-mail..." class="contact-subject" id="contact-subject">
</div>
<button type="submit" class="btn">Submit</button>
}
</div>
控制器......
public ActionResult RequestDemo()
{
return View();
}
[HttpPost]
public ActionResult DemoSubmit(LeadInfo leadInfo)
{
string salesEmail = CRMModels.GetNextSalesEmail();
ViewBag.Message = CRMModels.AddLeadToCRM(leadInfo);
if (ViewBag.Message == null)
{
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
return RequestDemo();
}
}
模特......
if (hsdRepId != Guid.Empty)
{
lead.Attributes["ree_hsdrepresentative"] = new EntityReference("ree_henryscheinrepresentative", hsdRepId);
service.Create(lead);
}
else
{
message = "Invalid HSD Representative Code";
}
return message;
在DemoSubmit函数中,如果有要显示的消息,我需要返回视图才能显示它。我怎么做?我尝试使用重定向,但这只是给了我一个新的页面,没有输入的数据,也没有显示消息。
谢谢, 加里
答案 0 :(得分:3)
在控制器出现错误后,您可以向modalState添加错误消息
ModelState.AddModelError("", "Invalid HSD Representative Code");
并弹出错误提示,您可以使用html扩展方法弹出消息
public static HtmlString PopAlert(this HtmlHelper htmlHelper, string alertType = "danger",
string heading = "")
{
if (htmlHelper.ViewData.ModelState.IsValid)
return new HtmlString(string.Empty);
var sb = new StringBuilder();
sb.AppendFormat("<div class=\"alert alert-{0} alert-block\">", alertType);
sb.Append("<button class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>");
if (!heading.IsNullOrWhiteSpace())
{
sb.AppendFormat("<h4 class=\"alert-heading\">{0}</h4>", heading);
}
sb.Append(htmlHelper.ValidationSummary());
sb.Append("</div>");
return new HtmlString(sb.ToString());
}
在视图中,您只需像这样调用Html扩展方法
@Html.PopAlert()
希望这会对你有所帮助:)。
答案 1 :(得分:2)
您的代码存在许多问题,特别是您没有将任何控件绑定到模型的事实,因此返回视图将始终显示空控件。您还应该在属性中包含验证属性,以防止发布和保存可能有害的数据。您的视图也会生成无效的html(许多重复的id
属性)和<label>
标签,这些标签并非真正的标签(点击它们不会将焦点设置为关联的控件,因为您没有将它们与控制。
根据您的观点,您的LeadInfo
类看起来像(添加建议的属性)
public class LeadInfo
{
[Display(Name = "HSD Rep code")]
[Required(ErrorMessage = "Please enter your HSD Rep code")]
public string hsdrepcode { get; set; }
[Display(Name = "Rep first name")]
[Required(ErrorMessage = "Please enter your Rep first name")]
public string hsfirstname { get; set; }
.....
[Display(Name = "Doctor's e-mail")]
[Required(ErrorMessage = "Please enter your doctor's e-mail")]
[EmailAddress]
public string emailaddress{ get; set; }
}
然后你应该
public ActionResult RequestDemo()
{
LeadInfo model = new LeadInfo();
return View(model);
}
然后视图应强烈输入html helper以绑定到您的属性并显示验证错误
@model LeadInfo
....
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true) // this is where you custom error message will be displayed
@Html.LabelFor(m => m.hsdrepcode) // displays the text associated with the DisplayAttribute and is associated with the following textbox
@Html.TextBoxFor(m => m.hsdrepcode, new { placeholder="Enter your HSD Rep code...", @class="contact-name"})
@Html.ValidationMessageFor(m => m.hsdrepcode)
....
<button type="submit" class="btn">Submit</button>
}
您还应该包含以下脚本(最好使用@Scripts.Render()
以及MVC的捆绑和缩小功能)
jquery-{version}.js
jquery.validate.js
jquery.validate.unobtrusive.js
您还应该使用布局(母版页)
后方法是
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestDemo(LeadInfo model) // not sure why you would change the name of the method?
{
if(!ModelState.IsValid)
{
return View(model); // return the view to fix any validation errors
}
string errorMessage = CRMModels.AddLeadToCRM(leadInfo);
if (errorMessage == null)
{
string salesEmail = CRMModels.GetNextSalesEmail();
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", errorMessage);
return View(model);
}
}
您不清楚要返回的错误消息是什么,但您的代码表明它可能与hsdrepcode
属性相关联,在这种情况下,修改代码以将错误与特定属性相关联
ModelState.AddModelError("hsdrepcode", errorMessage);
旁注:您的大多数代码都忽略了使用MVC的好处,以至于您可能不会使用它。我建议你去MVC网站并完成教程,