我對ASP.NET比較陌生,所以請耐心等待。如何使用ASP.Net/ MVC 5/EF編碼拍賣網站
我試圖編寫一個簡單的慈善拍賣網站,使用MVC 5和實體框架Code-First。
我已經創建了一個Item模型和控制器。該項目模型認爲,如標題,描述字段,起拍,當前出價,出價,最高出價者的數量等
public class Item
{
public int ID { get; set; }
public string Code { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[DisplayName("Starting Bid")] public int StartingBid { get; set; }
public int Increment {get; set;}
public int Bids { get; set; }
[DisplayName("Current Bid")] public int CurrentBid { get; set; }
public string HighBidder { get; set; }
public int CurrentOrStartingBid
{ // The price that is displayed next to an item
get
{
return Bids > 0 ? CurrentBid : StartingBid;
}
}
public int NextBid
{ // The minimum amount that is valid for a new bid
get
{
return Bids > 0 ? CurrentBid + Increment : StartingBid;
}
}
}
(我曾試圖在上面的代碼做的是增加這些屬性CurrentOrStartingBid和NextBid,它們不打算成爲數據庫記錄的一部分,它們只是派生屬性而不是數據庫中的列,所以希望將這些屬性設置爲只讀屬性可以......)
我現在正在製作項目細節的視圖。這顯示了物品描述,並且還提供了用於出價的表單控件,類似於您在eBay上看到的內容。我的問題是關於如何正確連接投標按鈕的邏輯。
我認爲在視圖中,我應該使用帶有提交按鈕的HTML表單進行出價。當按鈕被擊中時,它會執行一個HTTP帖子,並允許我在當時被調用的Item控制器中編寫一個方法。
所以在視圖中我的剃刀代碼目前看起來是這樣的:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="number" class="form-control" value="@Model.NextBid" id="CurrentBid" name="CurrentBid"/>
</div>
<br />
<button type="submit" class="btn btn-primary btn-lg">Place bid</button>
</div>
}
使用這個代碼讓我寫一個控制器的方法與此簽名:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid([Bind(Include = "ID,CurrentBid")] Item item)
這種作品至今。但請注意,在服務器端驗證之前,我必須傳遞該項目的CurrentBid字段中出價的金額。這對我來說並不完全正確。有沒有寫這個方法的方法,所以它只需要這樣的簽名?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid(int itemID, int bidAmount)
也許有辦法做到這一點與查詢字符串或東西嗎?
無論如何,一旦進入方法,事情似乎有點奇怪。防止過量發佈,item
變量中唯一有效的字段是ID
和CurrentBid
。因此,我然後在DbContext中查找與該ID對應的實際項目並更新它:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid([Bind(Include = "ID,CurrentBid")] Item item)
{
if (ModelState.IsValid)
{
Item i2 = db.Items.Find(item.ID);
if (item.CurrentBid >= i2.NextBid)
{
i2.Bids++;
i2.CurrentBid = item.CurrentBid;
i2.HighBidder = HttpContext.User.Identity.Name;
db.Entry(i2).State = EntityState.Modified;
db.SaveChanges();
}
return View(i2);
}
return RedirectToAction("Auction");
}
這似乎工作。但它感覺不對。我想我在這裏錯過了一些重要的概念/模式。如果有經驗的MVC人員可以勾勒出他們如何連接這個簡單按鈕的客戶端/服務器邏輯,那就太棒了。 (你也會幫助一個很好的事業!)
感謝您抽出寶貴的時間。我有一些後續問題: 1.在Bid方法中,您將如何更新數據庫?使用db.Items.Find(itemID)? 2. Ajax.BeginForm()在Html.BeginForm()上面給你什麼? 3.您如何對出價金額進行基本的客戶端驗證? 非常感謝! –
如果我目前的答案幫助你解決目前的問題,我會很高興。對於所有其他新問題,請啓動新主題,以免混淆其他讀者。順便說一下,如果你解決了現在的問題,那麼請標記爲答案,這樣它會幫助別人找出答案。 – ramiramilu