开发者

How to get MVC remote validation working

I have an Invoice Model which has an areaId property:

public class Invoice : IEntity, IValidatableObject
    {
        ...

        [Required(ErrorMessage = "Region is a required field.")]
        [Display(Name = "Region:")]
        [Remote("Check","Invoice")]
        public virtual int? AreaId { get; set; }

...

So, I'm trying to get the remote validation working on AreaId.

In my invoice controller I set up:

p开发者_JS百科ublic void Check(int id)
        {

        }

which I expected would get hit when I did an insert for an Invoice as it would try to validate.

Nothing happened when I validated.

I checked fiddler and it had an HTTP 500 error trying to get to /Invoice/Check/Invoice.AreaId=1

It never got to my check method. I did however manually type in the URL Invoice/Check/1 and it got there alright.

Anyone know what I'm doing wrong? It's like it's constructing the Url all wrong.


The Url you are looking to create should actually be /Invoice/Check?AreaId=1 since you are passing the AreaID. I'm not sure if they are the cause but having both a virtual property and a function that returns void could be messing with the remote validation so change the function to return JsonResult and make the property non-virtual. Change the parameter in the Check function to AreaId rather than id. Also, if you have created custom routes they could be stuffing it up.

Try following this: http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx. Especially the section entitled Adding Custom Remote Validation.


Well, the 500 code is because your ajax url would be /Invoice/Check?AreaID=1 whereas you are accepting id in method signature, which also happens to be non nullable. This is why exception is thrown and you get 500 code on client side.
Second thing, void method would not server your purpose here because it would not send back a value to client side. However, i can't imagine that it could be the source of exception in my wildest dreams. Furthermore, you can set return type to JsonResult, String or ContentResult to send an appropriate value to the client so it can check against it for validity.

public string Check(int AreaID)
{
  return "true";
}

public JsonResult Check(int AreaID)
{
   return Json(true);
}
public ContentResult Check(int AreaID)
{
   return Content("True");
}

one more thing, when you manually type Invoice/Check/1, 1 is assigned to id route value if you have not removed (and i bet you haven't) default route that comes with mvc app. This way non nullable parameter id gets value and no exception is thrown.


Ended up using

[Bind(Prefix = "EditInvoiceViewModel.ActivityId")]

from

How to use Bind Prefix?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜