2

私のコントローラーは次のような JsonResult を返します。

return Json(model);

クライアントに送り返す前に、その場でjsonデータを変更するにはどうすればよいですか。モデルに検証属性を追加したいので、最終的には次のようになります。

{"Label": "Test", 
  "ValidationRules":[{"data-val-required":"This field is required.", "data-val-length-max":25, "data-val-length":"Max 25 chars." }]}

アップデート

public class Product
{
  [Required]
   String Label {get; set;}
}

model が Product のインスタンスである Json(model) を呼び出す場合、返される前に json 文字列を変更して、検証属性が含まれるようにしたいと思います。

4

1 に答える 1

1

ValidationRules プロパティを持つ ValidatableBase という基本クラスを作成してみませんか。

public class Product : ValidatableBase
{
    public string Label { get; set; }
}

public abstract class ValidatableBase
{
    public ValidatableBase()
    {
        this.ValidationRules = new Dictionary<string, string>();
    }
    public Dictionary<string, string> ValidationRules { get; set; }
}

public ActionResult GetProduct()
{
    var product = new Product();
    product.Label = "foo";
    product.ValidationRules.Add("data-val-required", "this field is required");

    return Json(product);
}

このクラスから継承してシリアライズします。

または、DataAnnotations を使用している場合は、ASP.NET MVC が提供する既定の jQuery 検証と HtmlHelper メソッドを使用しないでください。

于 2013-03-22T16:29:32.227 に答える