用戶能夠將服裝(影像/圖片)發布到網站。如果用戶想要發布服裝,他需要給服裝一些值。裝備需要有:價格、標題、路徑(來自檔案資源管理器)和類別(這是一個列舉)。
可以通過下拉選單選擇類別,標題和價格通過文本框給出值。
所以結論是,為了能夠發布服裝,您需要上傳一張圖片并在同一個視圖中為該圖片賦予一些值。如果其中一個屬性未指定值(例如,未選擇影像,或未指定價格),則應該出現錯誤:缺少其中一個欄位。
當所有屬性都被賦予一個值時,具有給定值的裝備進入資料庫。
這是我的服裝模型:
public class OutfitVM
{
public enum OutfitCategory
{
Trendy,
Chic,
Oldschool,
Casual
}
[Required]
public int? Prijs { get; set; }
[Required]
public string? Titel { get; set; }
public string? FileAdress { get; set; }
[Required]
public OutfitCategory? DeCategory { get; }
public bool Retry { get; set; }
//public List<Review> Reviews { get; set; } = new List<Review>();
public OutfitVM(string titel, int prijs, string fileadress, OutfitCategory
category)
{
this.Titel = titel;
this.Prijs = prijs;
this.FileAdress = fileadress;
DeCategory = category;
}
public OutfitVM()
{
}
}
這是迄今為止的控制器:
public class ToevoegController : Controller
{
private readonly ILogger<ToevoegController> _logger;
public ToevoegController(ILogger<ToevoegController> logger)
{
_logger = logger;
}
public ActionResult OutfitToevoegen() //IActionresult is een interface en
actionresult is een implimentatie daarvan
{
OutfitVM outfitVM = new OutfitVM();
outfitVM.Retry = false;
return View(outfitVM);
//dit uitleg? wrm maak je nieuwe vm aan en wrm geef je die mee aan view
}
[HttpPost]
public IActionResult OutfitToevoegen(OutfitVM outfit)
{
}
}
因此,在 HttpPost 方法中應該有一些代碼告訴程式如果我前面提到的一個或多個屬性沒有被賦予值時給出錯誤。
OutfitCategory = category (which is chosen via a drop down menu)
Prijs = price (which is given a value via a textbox)
Title = title (which is given a value via a textbox)
FileAdress = path (which is automatically given a value when the user chooses a picture from file explorer)
一旦服裝的每個屬性都被賦予了一個值,那么服裝(影像)和與之關聯的值就會進入資料庫。
謝謝!
uj5u.com熱心網友回復:
"So inside the HttpPost method there should be some code wich tells the program to give an error if one or more of the attributes i mentioned earlier is not given a value?"
有很多方法可以做到這一點。一個是
Note:如果您檢查捕獲的螢屏截圖,您會看到當我發送空請求時它回應
400說驗證失敗,如下所示:
因此,使用
[Required]注釋您可以處理此問題,而無需為此撰寫任何額外的驗證代碼。[Required]因為你的controller action論點會這樣做。希望這會幫助您相應地嘗試實施。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/479171.html
標籤:asp.net-mvc asp.net 核心 asp.net-core-webapi .net-6.0
下一篇:如何將引數傳遞給MVC控制器?


