我为我的开发类构建了一个小型MailApplication,这是一项家庭作业,但我似乎无法解决这个错误。
我基于模型(Mail)生成了一个新的Controller(MailController)。一切正常,邮件正在发送,但是当我return View("Index", mailModel);
时,我在提交网址/邮件/创建(POST)表单时收到错误。
The model item passed into the dictionary is of type 'WebApplication1.Models.Mail', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WebApplication1.Models.Mail]'.
以下是MailController的Create方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult Create([Bind(Include = "ID,From,To,Subject,Body")] Mail mail, Models.Mail mailModel)
{
if (ModelState.IsValid)
{
//Create mail
MailMessage message = new MailMessage();
message.To.Add(mailModel.To);
message.From = new MailAddress(mailModel.From);
message.Subject = mailModel.Subject;
message.Body = mailModel.Body;
message.IsBodyHtml = true;
//Setup host
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("something@gmail.com", "password!");
smtp.EnableSsl = true;
//Send the EMail
smtp.Send(message);
return View("Index", mailModel);
}
else
{
return View(mailModel);
}
}
以下是我的模特:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class Mail
{
public int ID { get; set; }
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
最后一件事,我的观点:
@model IEnumerable<WebApplication1.Models.Mail>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.From)
</th>
<th>
@Html.DisplayNameFor(model => model.To)
</th>
<th>
@Html.DisplayNameFor(model => model.Subject)
</th>
<th>
@Html.DisplayNameFor(model => model.Body)
</th>
<th></th>
</tr>
@foreach (var item in ViewData.Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.From)
</td>
<td>
@Html.DisplayFor(modelItem => item.To)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
答案 0 :(得分:1)
正如f0x已经指出的那样,你的模型和视图没有对齐。
您可以将视图的模型定义更改为:
@model WebApplication1.Models.Mail
或者为视图提供动作列表。
在这里你需要提供清单:
return View(listOfMailModel);