0

I have a partial view that contains a registration form with the following fields:

  1. E-Mail
  2. First Name
  3. Last Name
  4. Password

I am posting the form using jQuery Ajax without using View Model.

Question : Is it a good approach to not use View Model in his context ?

Question : Is my approach useless in case of unit test cases?

jQuery

$.ajax({
    url: "@Url.Action("Action", "Controller", new { area = "Area" })",
    type: "POST",
    contentType: 'application/json; charset=utf-8', 
    dataType: "json",
    data: JSON.stringify({mail : "mails", nam : nam ......}),
    traditional: true,
    success: function (data) {
        alert("wsaved");
    }
});

[HpPost]
public Actionresult abc(string mail, string nam, sring lasnam)
{
     return Json(new {succss = ru});
}
4

2 回答 2

1

在他的上下文中不使用 View Model 是一个好方法吗?

不,这会使验证变得更加困难。假设您想要验证该电子邮件不是空的并且确实是一个有效的电子邮件地址。如果您使用了视图模型,您所要做的就是Email使用正确的验证属性来装饰视图模型上的属性。使用您的方法,您现在必须为此在控制器操作中编写几行无用的代码。

以下是您的视图模型的外观:

public class RegisterUserViewModel
{
    [Required]
    [RegularExpression("PUT YOUR REGEX TO VALIDATE AN EMAIL HERE")]
    public string Email { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    [Required]
    [RegularExpression("PUT YOUR REGEX TO ENFORCE SOME PASSWORD STRENGTH")]
    public string Password { get; set; }
}

现在您的控制器操作变为:

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (!ModelState.IsValid)
    {
        // validation failed

        var errors = ModelState
            .Where(x => x.Value.Errors.Count > 0)
            .Select(x => new 
            { 
                Key = x.Key, 
                Errors = x.Value.Errors.Select(e => e.ErrorMessage) 
            }
        );

        return Json(new { success = false, errors = errors });
    }

    return Json(new { success = true });
}
于 2013-08-26T15:55:44.873 回答
0

如果您在 MVC 4 中使用 ApiController,那么您可以使用模型来绑定,它将使用(默认情况下)Newton Json.NET。

响应模型

[DataContact]
public class ResponseModel
{
    [DataMember]
    public string Status { get; set; }
}

行动模型

[DataContact]
public class RegisterUserViewModel
{
    [Required]
    [DataMember(isRequired=true)]
    public string Email { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [Required]
    [DataMember(isRequired="true")]
    public string Password { get; set; }
}

ApiController 动作

[HttpPost]
public ReponseModel Register(RegisterActionModel actionModel)
{
    if (this.ModelState == valid)
    {
        //do stuff
        return new ResponseModel()
        {
            Status = "OK"
        };

    }
    else
    {
        return new ResponseModel()
        {
             Status = "Invalid Data"
        }
    }
} 
于 2013-08-26T16:28:32.843 回答