我正在尝试使用MVC 3验证IP地址。如果用户输入了错误的IP地址,那么页面应该显示"错误的IP地址消息"给用户。我在互联网上搜索了很多,但没有得到适当的解决方案。 你能帮我么... 提前谢谢。
模型代码:
[Display(Name = "EQ")]
public string EQ { get; set; }
[Display(Name = "EQD")]
public string EQD { get; set; }
[Display(Name = "BFX")]
public string BFX { get; set; }
[Display(Name = "SLB")]
public string SLB { get; set; }
[Display(Name = "Others")]
public string Others { get; set; }
我想要单独的5个复选框,即(EQ,EQD,BFX,SLB和其他)。
观点:
<div class="editor-label" style="font-weight: bold">
@Html.LabelFor(model => model.EQ)
</div>
<div class="editor-field">
@Html.CheckBoxFor(Model => Model.EQ)
@Html.ValidationMessageFor(model => model.EQ)
</div>
<div class="editor-label" style="font-weight: bold">
@Html.LabelFor(model => model.EQD)
</div>
<div class="editor-field">
@Html.CheckBoxFor(Model => Model.EQD)
@Html.ValidationMessageFor(model => model.EQD)
</div>
<div class="editor-label" style="font-weight: bold">
@Html.LabelFor(model => model.BFX)
</div>
<div class="editor-field">
@Html.CheckBoxFor(Model => Model.BFX)
@Html.ValidationMessageFor(model => model.BFX)
</div>
<div class="editor-label" style="font-weight: bold">
@Html.LabelFor(model => model.SLB)
</div>
<div class="editor-field">
@Html.CheckBoxFor(Model => Model.SLB)
@Html.ValidationMessageFor(model => model.SLB)
</div>
<div class="editor-label" style="font-weight: bold">
@Html.LabelFor(model => model.Others)
</div>
<div class="editor-field">
@*@Html.EditorFor(model => model.Others)*@
@Html.CheckBoxFor(Model => Model.Others)
@Html.ValidationMessageFor(model => model.Others)
</div>
答案 0 :(得分:1)
我建议使用 IPAddress.TryParse()
确定字符串是否是有效的IP地址。
http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse(v=vs.110).aspx
答案 1 :(得分:1)
在你的模特中
[正则表达式(@&#34; ^(?:[0-9] {1,3}){3} [0-9] {1,3} $&#34)]
public string AssignedIP {get;组; }
答案 2 :(得分:1)
这个人对MVC有很好的方法 https://codingjourneyman.com/2015/01/08/model-validation-in-asp-net-mvc/
public class IPAddressModel
{
[Required]
[Display(Name = "Your name")]
public string Name { get; set; }
[IpAddress]
[Required]
[Display(Name = "Your IP address")]
public string IPAddress { get; set; }
}