【发布时间】:2014-02-13 19:17:12
【问题描述】:
我有两种形式:一种用于注册时事通讯,另一种用于在网站上搜索: http://nsa31.casimages.com/img/2014/02/13/140213065557598803.png
因为我需要验证客户端和服务器端,所以我为每个表单创建了 2 个 ViewModel 来指定验证属性和错误消息:
订阅模型(文件:SubscribeModel.cs):
using System.ComponentModel.DataAnnotations;
namespace SoscomAppMvc.Models
{
public class SubscribeModel
{
[Required(ErrorMessage = "Veuillez saisir votre adresse mail pour s'inscrire ...")]
[EmailAddress(ErrorMessage = "Veuillez saisir une adresse mail valide \"Ex: mail@domaine.com\"")]
public string SubEmail { get; set; }
}
}
搜索模型(文件:SearchModel.cs):
using System.ComponentModel.DataAnnotations;
namespace SoscomAppMvc.Models
{
public class SearchModel
{
[Required(ErrorMessage = "Veuillez saisir votre mot clé avant de lancer la recherche ...")]
public string Key { get; set; }
}
}
这两种形式从 2 个局部视图渲染到 Layout 视图中:
订阅部分视图(文件:Shared/Subscribe.cshtml):
@model SoscomAppMvc.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Soscom"))
{
@Html.TextBoxFor(m => m.SubEmail, new { placeholder = "Email pour s'inscrire à la newsletter", @class = "subscribebox" })
<input class="subscribeBtn" type="submit" value="s'inscrire">
@Html.ValidationMessageFor(m => m.SubEmail)
}
搜索局部视图(文件:Shared/Serach.cshtml):
@model SoscomAppMvc.Models.SearchModel
@using (Html.BeginForm("Search", "Soscom", FormMethod.Get))
{
@Html.TextBoxFor(m => m.Key, new { placeholder = "Rechercher un produit, une solution ...", @class = "textfeild" })
<input class="searchbutton" type="submit" value="Go">
}
将这两个部分视图渲染到布局页面的代码(文件:Shared/_Layout.cshtml)
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
<header>
<div id="banner">
@Html.Partial("~/Views/Shared/Subscribe.cshtml")
</div>
<div id="navpan">
<nav>
<ul>
<li>@Html.ActionLink("Soscom", "Index", "Soscom")</li>
....
</ul>
</nav>
<div id="searchbar">
@Html.Partial("~/Views/Shared/Search.cshtml")
</div>
</header>
....
<section>
@RenderBody()
</section>
....
</body>
</html>
我还创建了 2 个操作来处理发布的数据:
订阅操作:
[HttpPost]
public ViewResult Subscribe(SubscribeModel model)
{
if (!ModelState.IsValid)
return View("SubscribeErrors", model);
// saveMailToDB(model.SubEmail)
return View("SubscribeResult", model);
}
搜索操作:
[HttpGet]
public ViewResult Search(SearchModel model)
{
if (!ModelState.IsValid)
return View("SearchErrors", model);
// searchFromDB(key, ResultSearchModel); return View(ResultSearchModel);
return View("SearchResult");
}
现在当我运行应用程序时,一切看起来都很好,但是当我发布订阅表单时出现此错误:
The model item passed into the dictionary is of type "SubscribeModel", but this dictionary requires a model item of type "SearchModel"
我在搜索表单中遇到同样的错误:
The model item passed into the dictionary is of type "SearchModel", but this dictionary requires a model item of type "SubscribeModel"
如何摆脱这个错误,
谢谢
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor