gpt4 book ai didi

asp.net-mvc - 在我养成坏习惯之前需要建议

转载 作者:行者123 更新时间:2023-12-04 15:15:37 25 4
gpt4 key购买 nike

我有一个名为 AuctionsController 的 Controller 。在其中,我有名为 Index() 和 AuctionCategoryListing() 的操作:

//Used for displaying all auctions.
public ActionResult Index()
{
AuctionRepository auctionRepo = new AuctionRepository();
var auctions = auctionRepo.FindAllAuctions();
return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
AuctionRepository auctionRepo = new AuctionRepository();
var auctions = auctionRepo.FindAllAuctions()
.Where(c => c.Subcategory.Category.Name == categoryName);
return View("Index", auctions);
}

如您所见,它们都调用相同的 View (此操作是否称为“调用 View ”。它的正确名称是什么?)。
@model IEnumerable<Cumavi.Models.Auction>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
IDSubcategory
</th>
<th>
IDCity
</th>
<th>
IDPerson
</th>
<th>
Title
</th>
<th>
TextBody
</th>
<th>
ContactNumber
</th>
<th>
AskingPrice
</th>
<th>
AddressDirection
</th>
<th>
LatestUpdateDate
</th>
<th>
VisitCount
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
<td>
@item.IDSubcategory
</td>
<td>
@item.IDCity
</td>
<td>
@item.IDPerson
</td>
<td>
@item.Title
</td>
<td>
@item.TextBody
</td>
<td>
@item.ContactNumber
</td>
<td>
@String.Format("{0:F}", item.AskingPrice)
</td>
<td>
@item.AddressDirection
</td>
<td>
@String.Format("{0:g}", item.LatestUpdateDate)
</td>
<td>
@item.VisitCount
</td>
</tr>
}

</table>

它们都继承自同一个模型。

我的问题是,我是否以正确的方式做事?或者这只是我设法拼凑起来的一个黑客。在我养成坏习惯之前帮助我。

最佳答案

我会将其修改为:

public ActionResult Index(string categoryName)
{

AuctionRepository auctionRepo = new AuctionRepository();
var auctions=auctionRepo.FindAllAuctions();

if (!string.IsNullOrEmpty(categoryName))
{
auctions = auctions.Where(c => c.Subcategory.Category.Name == categoryName);
}

return View(auctions);
}

您的路线可能如下所示:
    context.MapRoute(
"auction_defalt",
"Auction/{categoryName}",
new { controller="Auction", action = "Index", categoryName = UrlParameter.Optional }

由于 Action 如此相似,我认为没有理由将它们分开。

关于asp.net-mvc - 在我养成坏习惯之前需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4442844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com