Clinetside在MVC3中使用JQuery的验证

时间:2011-11-19 09:28:51

标签: jquery asp.net-mvc-3

这些是我的模特。

public class Question
{

private string _questionNo;  
private string _questionText; 
private List<Option> _options;

public List<Option> Options
{
    get { return _options; }
    set { _options = value; }
}
public string QuestionNo
{
    get { return _questionNo; }
    set { _questionNo = value; }
} 
public string QuestionText
{
    get { return _questionText; }
    set { _questionText = value; }
} 

}

公共类选项 {

private string _optionText; 
private string _optionNumber; 
public string OptionText
{
    get { return _optionText; }
    set { _optionText = value; }
}
public string OptionNumber
{
    get { return _optionNumber; }
    set { _optionNumber = value; }
} 
}

这些是我的控制器

   public ActionResult GetQuestion(int id,string gid)
    { 
        var vewmodel = ques.GetQuestion(Gid, Uid, id);
        return View(vewmodel);
    }

这是我的观点。

     @model mobilesurveys.mt.Models.Question  
     @{ ViewBag.Title = "Question"; }
    <div data-role="header" data-theme="b">
     <h1>
    @Model.SurveyName</h1>
    </div>
   @if (@Model.QuestionType == 7)
   {   
<div data-role="fieldcontain">
    @using (Html.BeginForm("SaveDropDown", "GetQuestion", Model))
    {
        @Html.AntiForgeryToken()

        <fieldset>
            <label class="select">@Model.QuestionText
            </label>
            <br />
            <select name="selectedObjects" id="selectchoice1" data-native-menu="false">
                <option value="--select--">--Select--</option> 
                @foreach (var item in Model.Options)
                {

                    if (@item.IsAnswer == true)
                    {
                    <option selected="selected"  value="@item.OptionNumber">@item.OptionText</option>
                    }
                    else
                    {
                    <option  value="@item.OptionNumber">@item.OptionText</option>
                    }

                }
            </select>
        </fieldset>
        <p>
            <input type="submit" value="Next" />
        </p>
    }
    </div>
   }

所以我基于QuestionTypeId(RadioButtions,CheckBoxes,TextBox,Select)绑定了optoins。现在我想在客户端验证数据。我正在使用Jquery Scripts。

我如何编写验证。任何帮助表示赞赏。

感谢。

1 个答案:

答案 0 :(得分:1)

有两种方法。 1.您可以通过在模型类中添加注释来完成此操作 在模型中添加如此行

[Required(ErrorMessage = "Title is required"), StringLength(230)]

以这种方式在变量上方添加注释。

或者 2.您可以使用jquery代码进行验证。 我给你的代码

$(document).ready(function () {
        $("#SubmitForm").click(function (e) {
            var textContent = $("#TextContent").val();
            textContent = jQuery.trim(textContent);
            if (textContent == "") {
                alert("Content field cannot be empty.");
                $("#TextContent").focus();
                return false;
            }


        });
    });

通过这种方式,您可以在jquery中检查字段。 如果您发现任何疑问,请回复我

相关问题