iT邦幫忙

0

ModelState.IsValid的證問題

  • 分享至 

  • xImage

請教大家以下兩個errMsg裏面寫的是什麼意思,謝謝

1.第1個

if (ModelState.IsValid)
{
}
{
	var _errMsg = ModelState.Values.Where(x => x.Errors.Count > 0)?.FirstOrDefault()?.Errors.Select(y => y.ErrorMessage).FirstOrDefault();
	return Content(HttpStatusCode.BadRequest, _errMsg);
}

2.第2個

if (ModelState.IsValid)
{
}
else
{
	var _errMsg = string.Join("; ", ModelState.Values
						.SelectMany(x => x.Errors)
						.Where(x => !string.IsNullOrEmpty(x.ErrorMessage))
						.Select(x => x.ErrorMessage));
	return Content(HttpStatusCode.BadRequest, _errMsg);
}
先習慣用程式標簽吧。
Homura iT邦高手 1 級 ‧ 2021-12-09 13:14:42 檢舉
只是把ModelState裡面的Eroor msg抓出來...
還要像星空大說的一樣要用程式標籤...
Model做資料驗證
第一個只回傳第一個錯誤訊息,第二個把全部組成字串再回傳
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Samuel
iT邦好手 1 級 ‧ 2021-12-10 11:01:37
最佳解答

驗證分為前後端
一般在前端可能就是畫面一些js驗證
而到後端也就是Server-Side驗證
Controller部分 POST action method
可以透過ModelState.IsValid做驗證
Eroor msg一些錯誤或不符資訊
可藉由ViewModel當時Data Annotation定義的去捕獲

.NET Core第28天_ValidationMessageTagHelper和ValidationSummaryTagHelper的使用
https://coolmandiary.blogspot.com/2021/08/net-core28validationmessagetaghelper.html

.NET Core第29天_Model驗證配置準備流程_各種驗證資料註解使用方式_part1(Required,StringLength,MaxLength,MinLength,RegularExpression,Range,Compare)
https://coolmandiary.blogspot.com/2021/08/net-core29modelpart1.html

.NET Core第30天_Model驗證配置準備流程_各種驗證資料註解使用方式_part2(Remote,DataType,EmailAddress,Display,DisplayFormat驗證)
https://coolmandiary.blogspot.com/2021/08/net-core30modelpart2remotedatatypeemail.html

我要發表回答

立即登入回答