【问题标题】:I want to show error message when textbox is null in mvc3我想在 mvc3 中的文本框为空时显示错误消息
【发布时间】:2014-03-21 06:12:22
【问题描述】:

我有一个控制输入类型是文本,它将接受用户输入的 id。当用户没有输入任何 id 并且当他单击按钮以获取详细信息时,我必须显示“请在文本框中输入 id”的消息。所有这些东西都是在 mvc3 中设计的。现在请帮助我们,我们将如何做到这一点?我是 mvc3 的新手。

更新

这是我的 HTML 代码:

<div class="centerize">
   <input type="text" name="entryid" value="" placeholder="Enter valid id" style="height:30px; text-align: center"/>
</div> 
<div class="centerize" style="height:20px"></div>
<div class="centerize">
  <input type="submit" value="Submit" style="height: 30px; width: 100px"/>
</div> 
<div class="centerize">
   @Html.ValidationSummary()
</div>

【问题讨论】:

标签: c# asp.net razor asp.net-mvc-2


【解决方案1】:

如果您确实想使用 Javascript 验证:

 @Html.TextBoxFor(m=>m.userid,new {id="userid"})

JS:

$(#submit).click(function()
{
    var data=$("#userid").val();

     if(data.length==0)
     {
       alert("Please enter user id");
      return false;  
     }
});

如果您想为您的模型使用data annotations 进行验证,只需为您的模型使用[Required] 属性

字段userid

【讨论】:

    【解决方案2】:

    如果您想在服务器端执行此操作,请在字段中添加必填数据注释:

    [Required]
    public string UserId{get;set;}
    

    而且,如果您想在客户端执行此操作,请使用此脚本;

    <script>
    $('input:submit').click(function()
    {
        var $entryId=$('input[name="entryid"]').val();    
         if($entryId.trim()=="")
         {
           alert("Entry Id is required!");
          return false;  
         }
    });
    </script>
    

    【讨论】:

    • @Html.ValidationSummary()
    • 当我点击按钮而不在文本框中输入 id 时,不显示错误消息。请检查我的代码
    • 你想在客户端做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多