我已经创建了Web表单,现在我希望将这些数据存储在数据库中,然后通过电子邮件将表单发送到电子邮件中。这不起作用,因为它一直告诉我在' /'中存在服务器错误。应用。即使我重定向到Thankyou页面,我也包含了感谢页面的代码。请告诉我我做错了什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nordstromapp.Models;
public SupportController(){
_db = new NordstromEntities();
}
//
// GET: /Form/[HttpGet]
public ActionResult Create()
{
var categoryList = new SelectList(new[] {"How the Site Looks",
"Product Offered", "How the site works", "General Comment"});
ViewBag.CategoryList = categoryList;
var concernList = new SelectList(new[] {"Shoes", "Handbags and accessories", "Beauty and Fragrance", "Sales",
"Designe Collection",
"Kids and Babies' collection", "Home gifts", "Service", "Other"});
ViewBag.ConcernList = concernList;
return View();
}
[HttpPost]
public ActionResult Create(Models.Support support)
{
if (string.IsNullOrWhiteSpace(support.Question))
{
ModelState.AddModelError("Question", "Question is required");
}
if (ModelState.IsValid)
{
// save to the database
return Redirect("Thankyou.cshtml");
}
return Create();
}
}
查看:
@model Nordstromapp.Models.Support
@{
var Question = Request["Question"];
var First_name = Request["First_name"];
var Last_name = Request["Last_name"];
var Telephone_number = Request["Telephone_number"];
var Email = Request["Email"];
var errorMessage = "";
var debuggingFlag = false;
try {
// Initialize WebMail helper
WebMail.SmtpServer = "localhost";
WebMail.SmtpPort = 21;
WebMail.UserName = "";
WebMail.Password = "";
WebMail.From = "";
// Send email
WebMail.Send(to: Email,
subject: "Help request from" + First_name,
body: Question
);
}
catch (Exception ex) {
errorMessage = ex.Message;
}}
<!DOCTYPE html> <html> <head> <title>Request for Assistance</title></head><br><body><br><p>Sorry to hear that you are having trouble, Mr/Ms <b>@Last_name</b>.</p>
@if(errorMessage == ""){<p>An email message has been sent to our customer service
department regarding the following problem:</p><p><b>@Question</b></p>}
else{<p><b>The email was <em>not</em> sent.</b></p>
<p>Please check that the code in the ProcessRequest page has correct settings for the SMTP server name, a user name,
a password, and a "from" address. </p>
if(debuggingFlag){
<p>The following error was reported:</p><p><em>@errorMessage</em></p> } } </body>
答案 0 :(得分:0)
马上,我发现你结束行动的方式有几个问题。
您最后应该使用return RedirectToAction("Create")
或简单的return View()
,这样您就可以显示模型错误(如果您将助手添加到视图或验证区块中)。
您不应直接重定向到.chstml页面。取而代之的是return View("ThankYou")
,或者更好的是,重定向到显示该页面的Get操作。 (这是Post,Redirect,Get模式,以避免在用户刷新页面时重新发布数据的问题。)