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);
}

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; }
}

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();
}
}
- 3 回答
- 0 關注
- 253 瀏覽
添加回答
舉報