English 中文(简体)
mvc3 - ajax表格提交,服务器侧验证
原标题:mvc3 - ajax form submit and server side validation

我相信,这一点已经提出过,但我一直在努力找到所有解决办法,但任何解决办法都没有解决我的问题。 也许,我没有执行。

我正在使用MVC3、raz、 j。

我有一个新的用户登记表。 登记一旦成功,我想在辩证箱中显示成功的信息(对登记类型的不同)。

如果与《示范国家》有任何错误,则是指《示范国家》。 IsValid = 虚假,我想在Validation Summary中显示错误。

View

function OnBegin () { alert( begin ); return $( form ).validate().form(); }
function OnSuccess () { alert( success ); DisplaySucess()}
function OnFailure () { alert( failure ); }
function DisplaySuccess() {
    var typeOfRegistration = $( input:radio[name=RegistrationType]:checked ).val();
    var msg;
    if (typeOfRegistration == 0) {
        msg = "You are successfully enrolled for Algebra classes.";
    }
    if (typeOfRegistration == 1) {
        msg = "You are registered with your email address. Someone would contact you with an email.";
    }
    if (typeOfRegistration == 2) {
        msg = "Thank you for filling up this form. One welcome packet would be delivered with in next 15 days";
    }

    msg = msg.replace(/
/g,  <br /> );
    $( #dialog ).html(msg);
    $( #dialog ).dialog( open );
}
@model 示范法s.Registration示范法
@using (Ajax.BeginForm("NewRegistration", "Account", new AjaxOptions() { OnBegin="OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{ 
  @Html.ValidationSummary()
    <div>
    Register<br />
    @Html.RadioButton("RegistrationType ", "0", true) New Algebra class<br />
    @Html.RadioButton("RegistrationType ", "1") New user registration by email<br />
    @Html.RadioButton("RegistrationType ", "2") New user registration by mailing address<br/>
   ..some more types
</div>
<div>
    …here I display/hide controls based on Registration type selected.
        <div>
    @Html.LabelFor("UserName")
    @Html.TextBox("UserName")</div>
}

Controller

public ActionResult NewRegistration(Registration示范法 model)
{

         if (Request.IsAjaxRequest())
         {
             if (!示范法State.IsValid) { 
        //Ques: How do I display this in ValidationSummary. 
        return Json(new object[] { false, "Contains Email Address", 示范法State.GetAllErrors() }); 
        }
             else { 
        if (UserNameIsTaken){ 
            //Ques: This does not show in ValidationSummary
            示范法State.Add示范法Error("_FORM", "This username is already taken. Please pick a different username.");
        }
       }
    }
         else if (!示范法State.IsValid) { return View(model); }

}

示范法

public class Registration示范法: IValidatableObject
{
[Required] //this gets displayed in ValidationSummary as Client-side validation
    public string UserName { get; set; }
    .. and all fields here
}
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
        if (!string.IsNullOrEmpty(UserName) && UserName.Contains(EmailAddress)) {
            yield return new ValidationResult("Username cannot contain email address", new[] { "UserName" });
        }
    }

Web.config has

UnobtrusiveJavaScriptEnabled="true" and ClientValidationEnabled="true"

.js files included are

字母缩略语

字母缩略语

字母缩略语

字母缩略语

What am I missing here? Any alternative? Thanks in advance.

最佳回答

页: 1 认为张贴表格只会使客户出现错误。

服务器边错,需要通过Json归还,然后在标记上“ins”或便衣。

在这方面,你可以看到并下载一个全面的工作榜样。

问题回答

撰写主卷中的以下参考资料(内容:cshtml):

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.4.4.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>

在网上,伪造:

<appSettings>
<!--<add key="ClientValidationEnabled" value="true"/> (enable this when client-side validation is needed) -->
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

在模型中:

public class ValidUserNameAttribue : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    return (value != null && value.ToString() == "Bob");
  }
}

public class Customer
{
  [ValidUserNameAttribue(ErrorMessage = "please type user name as Bob")] /* for server side validation*/
  public string UserName { get; set; }
}

主计长:

public class HomeController : Controller
{
  [HttpGet]
  public ActionResult Index()
  {
    return View(new ValidationModel());
  }

  [HttpPost]
  public ActionResult Form(ValidationModel validationModel)
  {
    return PartialView(!ModelState.IsValid ? "Partial/_Form" : "Partial/_Success", validationModel);
  }
}

指数:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

@{
    ViewBag.Title = "ajax form submit and server side validation";
}


<div id="FormContainer">
    @Html.Partial("Partial/_Form")
</div>

形式观点:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

@using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainer" , OnSuccess = "$.validator.unobtrusive.parse( form );" }))
{

    <p>
        @Html.ValidationMessageFor(m => m.UserName) // (Error Message)
    </p>

    <p>
        @Html.LabelFor(m => m.UserName):
        @Html.EditorFor(m => m.UserName)
    </p>

    <input type="submit" value="Submit" />
}

成功观点:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

User name  @Model.UserName  is valid :)

http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC”rel=“nofollow” http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签