ASP.NET MVC 中的强类型控件

.NET MVC 页面中有许多强类型控件可以使用,也可以生成强类型视图。

常用的强类型控件:

@Html.LabelFor(m => m.SenderName);      <!-------<label id="SenderName" name = "SenderName" value="实际模型的值">------------------>
@Html.TextBoxFor(m => m.SenderName, new { @class="text-box short" }) 
<!---<input type="text" name="SenderName" id="SenderName" class="text-box short" value="...">------>
@Html.EditorFor(m => m.Title)//同上面的区别在于需要设置属性数据类型,并且只能输入此类型的数据,如果不设置默认是text
列如:
[DataType(DataType.Text)]//默认的
public string SenderName{ get; set; }
@Html.ValidationMessageFor(m => m.SenderName)  //验证控件,验证的regex写在实体属性上面

例如:
[Required(ErrorMessage = "Please supply a slug for this post")]
[RegularExpression("^[a-zA-Z0-9-]+$", ErrorMessage = "That's not a valid slug. Only letters, numbers and hypens are allowed.")]
public string SenderName{ get; set; }
 
 
@Html.HiddenFor(m => m.Slug) //<input type="hidden" id="Slug" name="Slug" value="....">
@Html.TextAreaFor(m => m.Markdown, new { @class = "text-box, wmd-input", @id = "wmd-input" }) //多行
@Html.RadioButtonFor(m => m.IsCodePrettified, false) No<br /> //单选

列如:

@Html.RadioButtonFor(model => model.Sex, 1, new {@checked=true})<label id="boy">男</label>  
@Html.RadioButtonFor(model => model.Sex, 2)<label id="gril">女</label>  
 
 
@Html.ActionLink("« Home", "Index", "Home") //<a href="Home/idnex"><<Home</a>
@Html.Raw() //将里面的内容通过html形式输出,而不是文本
例如
@Html.Raw("<script>alert('a');</script>");会弹出提示框a 
@using (Html.BeginForm(
      "Course", //actionName
      "Assign", //controllerName
      new { area = "School" }, //需要单独传的参数
      FormMethod.Get, 
      new { @class = "form_section", id = "form_course" })) {
        ...
     }


我认为更好的写法:
@using (Html.BeginForm()) { @Html.EditorFor(x => x.Foo) @Html.ValidationMessageFor(x => x.Foo) <input type="submit" value="OK" /> }

 
$(function () {
    $('form').submit(function () {
          if ($(this).valid()) {
           $.ajax({
            url: this.action,
           type: this.method,
           data: $(this).serialize(),
           success: function (result) {
             $('#result').html(result);
           } });
         }
         return false;
   }); });

 
 

以上很多并未进行测试和实践,如有错误,请在下面留言指正。谢谢

原文地址:https://www.cnblogs.com/sjyzz/p/9072754.html