asp.net的MVC如何通过完整的模型从视图到控制器 [英] asp.net mvc how to pass full model from view to controller
问题描述
我有这样的表视图中的
<table class='sendemailtable'>
@if (!string.IsNullOrEmpty(Model.CustomerName))
{
<tr>
<td style="font-size: 26px;">
@Html.Label(string.Empty, Model.CustomerName)
</td>
</tr>
}
<tr><td style="padding-top: 15px;">To:</td></tr>
<tr>
<td>
@Html.TextBoxFor(m => m.EmailTo)
@Html.ValidationMessageFor(m => m.EmailTo);
</td>
</tr>
<tr><td style="padding-top: 15px;">Subject:</td></tr>
<tr>
<td style="font-size: 22px;">
@Html.TextBoxFor(m => m.EmailBody)
</td>
</tr>
few more
<button style="..." type="submit">SEND</button>
</table>
这些都不是从模型中的所有项目,它有一些多个ID,不能在UI present,有一定的财产,只有吸气
These are not all items from model, it has some more ids which are not present in ui, have some property with only getter
public int OfferID;
public int SomeOfferID;
public int CustomerID;
#region Email
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect email")]
public string EmailTo;
private string emailBodyDefault;
public string EmailBody
{
get
{
if (string.IsNullOrEmpty(emailBodyDefault))
emailBodyDefault = string.Format("Hi,{1}please take a look. Offer ID: {0}{1}{1}Thanks", SomeOfferID, Environment.NewLine);
return emailBodyDefault;
}
set { emailBodyDefault = value; }
}
private string emailSubject;
[Required]
public string EmailSubject
{
get
{
if (string.IsNullOrEmpty(emailSubject))
emailSubject = string.Format("Offer ID: {0}", SomeOfferID);
return emailSubject;
}
set { emailSubject = value; }
}
#endregion
我想通过我的全模式控制器,以便能够从控制器的动作发送电子邮件。还需要验证用户的电子邮件,以及非空的对象时,用户点击发送。我怎样才能做到这一点?
I want to pass full my model to controller, to be able to send email from controller's action. Also need to validate user's email, and non-empty subject when user clicks send. How can i do this ?
推荐答案
如果你想提交完整的模型,那么你需要在你的表单模型的所有属性。为此,您可以使用 @ Html.HiddenFor(M = GT; m.YourPropertyName)
如果你不希望显示他们做。我没有看到你的code任何形式的标签,但我相信有一些?
If you want the complete model to be submitted, then you need to include all the model properties in your form. You can do this using @Html.HiddenFor(m => m.YourPropertyName)
if you don't want them to be displayed. I don't see any form tags in your code, but I assume there are some?
您已经验证你的模型属性,你使用了[必填] DataAnnotations,所以要检查这在服务器端,您需要检查ModelState.Valid当您发布的数据控制器。
You already have validation on your model properties as you've used the [Required] DataAnnotations, so to check this on the server side, you need to check ModelState.Valid when you post the data to your controller.
public ActionResult SubmitMyForm(MyModel model)
{
if (ModelState.IsValid)
{
...
回应评论:
形式会是这个样子:
@using (Html.BeginForm())
{
<table>
...
</table>
}
错误发生,因为使用
块里面,你不需要preFIX C#code与 @
。请参见这个答案一个解释。
The error is occurring because inside the using
block, you don't need to prefix C# code with @
. See this answer for an explanation.
这篇关于asp.net的MVC如何通过完整的模型从视图到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!