我有这种情况:
型号类:
public class ContatoModel
{
private string nome;
private string email;
private string telefone;
public ContatoModel()
{
}
public ContatoModel(string nome, string email, string telefone)
{
this.nome = nome;
this.email = email;
this.telefone = telefone;
}
public string Assunto { get; set; }
[Required(ErrorMessage = "Nome Obrigatório")]
public string Nome
{
get
{
return this.nome;
}
set
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Nome" });
nome = value;
}
}
[Required(ErrorMessage = "Email Obrigatório")]
public string Email { get; set; }
[Required(ErrorMessage = "Telefone Obrigatório")]
public string Telefone { get; set; }
public string Comentarios { get; set; }
}
一个视图:
@using (Html.BeginForm("EnviarContato", "Contato"))
{
<div style="float: left; margin-bottom: 15px;">
@Html.Label("Assunto")<br />
@Html.DropDownList("ddlAssunto", assuntos, new {@class="dropdown"})
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
@Html.Label("Nome Completo", new { @class = "textfield" })<br />
@Html.TextBox("txtNome", "", new { @class = "textfield" })
@Html.ValidationMessage("Nome", "*")
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
@Html.Label("Email")<br />
@Html.TextBox("txtEmail", "", new { @class = "textfield" })
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
@Html.Label("Telefone")<br />
@Html.TextBox("txtTelefone", "", new { @class = "textfield" })
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
@Html.Label("Comentários")<br />
@Html.TextArea("txtComentarios")
</div>
<div style="clear: both"></div>
<div style="float: left; margin: 2px 20px 0px 255px;">
@*<input type="image" src="/Content/images/button_send2.gif" />*@
<input type="submit" value="Enviar" title="Enviar" />
</div>
}
而控制器中的这个方法:
[HttpPost]
public ActionResult EnviarContato(FormCollection values)
{
try
{
string assunto = values["ddlAssunto"];
string nome = values["txtNome"];
string email = values["txtEmail"];
string telefone = values["txtTelefone"];
string comentarios = values["txtComentarios"];
model.Assunto = assunto;
model.Nome = nome;
model.Email = email;
model.Telefone = telefone;
model.Comentarios = comentarios;
EnviarContato();
return RedirectToAction("Index", new { envio = "OK" });
}
catch (ValidationException ex)
{
throw new ValidationException(ex.Message); //return RedirectToAction("Index", new { envio = "NOK" });
}
}
我不能做数据注释客户端的工作。ValidationException 发生在服务器端,但我想查看验证客户端消息,但它不起作用。jQuery 文件仍在我的母版页中加载。
另一个问题是我的视图有一个组合,由 assunto 变量加载,我不知道如何将其包含在验证中,以强制用户选择一个。
我的模型类不适用于数据实体。它只是接收表单值,验证,如果一切正常,发送电子邮件。