亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模型未驗證

模型未驗證

C#
瀟瀟雨雨 2021-11-14 15:42:33
所以,當為我的模型輸入文本時,它總是有效的,即使我明確要求它有一個 minLength,盡管它是空的或小于 minLength??#簆ublic class CommentaarCreate_VM{    public Stad Stad { get; set; }    [Required]    public Commentaar Commentaar { get; set; }}public class Commentaar{    [Key]    public int CommentaarId { get; set; }    [Required]    public string UserId { get; set; }     [Required]    public int StadId { get; set; }    [Required(AllowEmptyStrings=false, ErrorMessage="You need to enter a comment of valid length")]    [MinLength(5, ErrorMessage ="You need to enter a comment of valid length")]    public string CommentaarText { get; set; }    [Required]    [DataType(DataType.DateTime)]    public DateTime Tijdstip { get; set; }}看法:@model DataGent.Web.ViewModels.CommentaarCreate_VM@{ViewData["Title"] = "Create new comment";}<div class="row"><div class="col-md-4">    <form asp-action="Create">        <div asp-validation-summary="All" class="text-danger"></div>        <input type="hidden" asp-for="Stad.Id" />        <input type="hidden" asp-for="Stad.Naam" />        <input type="hidden" value="@Html.AntiForgeryToken()" />        <div class="form-group">            <label asp-for="Commentaar" class="control-label"></label>            <input asp-for="Commentaar" class="form-control" />            <span asp-validation-for="Commentaar.CommentaarText" class="text-danger"></span>        </div>        <div class="form-group">            <input type="submit" value="Save" class="btn btn-default" />        </div>    </form></div>控制器動作:public ActionResult Create(int id)    {        CommentaarCreate_VM vm = new CommentaarCreate_VM()        {            Stad = _dataGentService.GetStadFromId(id),            Commentaar = null        };        return View(vm);    }有什么我想念的嗎?我以為除了數據注釋之外的所有工作都是由 MVC 完成的?
查看完整描述

3 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

您的輸入是:


<input asp-for="Commentaar" class="form-control" />

您必須將 asp-for 從 Commentaar 更改為 Commentaar.CommentaarText 以便對其進行驗證:


<div class="form-group">

    <label asp-for="Commentaar.CommentaarText" class="control-label"></label>

    <input asp-for="Commentaar.CommentaarText" class="form-control" />

    <span asp-validation-for="Commentaar.CommentaarText" class="text-danger"></span>

</div>

更新:


在將 Commentaar 對象傳遞給視圖之前,在視圖模型中初始化它:


public ActionResult Create(int id)

{

    CommentaarCreate_VM vm = new CommentaarCreate_VM()

    {

        Stad = _dataGentService.GetStadFromId(id),

        Commentaar = new Commentaar()

    };


    return View(vm);

}


查看完整回答
反對 回復 2021-11-14
?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

一個好的做法是ModelState.IsValid在您的 post 方法上使用,以檢查正在發送的模型的屬性。也就是說, ModelState.IsValid 檢查您在模型上編寫的數據注釋。


[HttpPost]

    [ValidateAntiForgeryToken]

    public ActionResult Create([Bind("CommentaarText, Tijdstip")] int id, IFormCollection collection) //Bind = protect from overposting

    {

         if(ModelState.IsValid)

         {

             //If it is valid, do all your business logic, like creating a new entry.

         }

         else

         {

             //Handle it

             return View();

         }

    }

另一件事是我看到你使用ViewModels哪個好。因此,您可以將視圖模型作為操作的參數發送。你可以這樣做:


[HttpPost]

    [ValidateAntiForgeryToken]

    public ActionResult Create(CommentaarCreate_VM viewmodel)

    {

          if(ModelState.IsValid)

          {

               //It is valid

               //All your logic

          }

          else

          {

               //Not valid

               return View(Viewmodel model)

          }         

    }

通過這樣做,您必須將數據注釋添加到 CommentaarCreate_VM


  public class CommentaarCreate_VM

    {

        public Stad Stad { get; set; }

        [Required(AllowEmptyStrings=false, ErrorMessage="You need to enter a comment of valid length")]

        [MinLength(5, ErrorMessage ="You need to enter a comment of valid length")]

        public Commentaar Commentaar { get; set; }

    }


查看完整回答
反對 回復 2021-11-14
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

所以我至少找到了一些解決方案,但潛在的問題仍然存在。問題是在控制器中 Modelstate.IsValid 始終為真,即使某些模型不應該是有效的,所以它只是在重定向到另一個頁面之前執行我想要的操作。解決方案是,如果在控制器中檢查字符串是否為空或為空,則我可以使錯誤消息正常工作,如果是,則返回(viewmodel),然后使錯誤消息正常工作。顯然,Modelstate.IsValid 不應該返回真,我仍然不知道為什么會這樣。


[HttpPost]

    [ValidateAntiForgeryToken]

    public ActionResult Create([Bind("CommentaarText, Tijdstip")] int id, CommentaarCreate_VM viewModel, IFormCollection collection) //Bind = protect from overposting

    {

        try

        {

          //If incoming string is null or empty

            if (string.IsNullOrEmpty(collection["Commentaar"]))

            {

                return View(viewModel);

            }

//This always returns true. It really shouldn't, because otherwise I wouldn't need that earlier check. 

//If the model isn't valid in the View, this one should be false, right?

            if (ModelState.IsValid)

            {

                // Creating  object to POST

                //.....


                return RedirectToAction(nameof(Index));

            }


            return View();

        }

        catch

        {

            return View();

        }

    }


查看完整回答
反對 回復 2021-11-14
  • 3 回答
  • 0 關注
  • 253 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號