[英]Basic ASP.NET MVC query with parameter
我是ASP.Net MVC和MVC體系結構的新手。 我正在使用“數據庫代碼優先”方法構建一個簡單的應用程序。
我有一個食譜模型,其屬性名為cookId
,這是創建食譜的用戶的ID。
現在,我希望能夠將查詢字符串傳遞到我的頁面,並且僅獲取cookId與參數相同的食譜,並在我的視圖中列出i。
我該如何實現? 我應該把這個邏輯放在哪里? 在我的controller
或我view
?
好了,asp.net mvc可與路由或TableRoutes一起使用。 默認路由以以下格式創建: {controller}/{action}/{id}
。
因此,當您收到有關操作的請求時,可以從操作(在控制器上)的id
參數中檢索此id,並使用該值在數據庫中命中並獲取需要在View上顯示的所有記錄。 您可以嘗試一些類似的方法:
public ActionResult Recipes(string id)
{
IEnumerable<Recipe> list = _repository.GetRecipeByCookId(id); // this method should return list of Recipes
return View(list); // return your View called "Recipes" passing your list
}
您也可以使用Request.QueryString["Id"]
來獲取ID,但是在asp.net mvc中,這不是一個好習慣。 您可以在操作上使用參數並使用它。
在您的View上,您可以使用IEnumerable<Recipe>
鍵入它,並將其顯示在表上,例如:
@model IEnumerable<Recipe>
<table>
@foreach(var recipe in Model)
{
<tr>
<td>@recipe.Name</td>
<td>@recipe.CookId</td>
<td>@recipe.OtherProperties</td>
</tr>
}
</table>
要創建一個傳遞該ID的鏈接,您只需使用Html.ActionLink
,就像在View上那樣:
@Html.ActionLink("Text of You Link", "Action", "Controller", new { id = 5, another = 10 }, new { @class = "css class for you link" });
並且asp.net mvc將按照global.asax上設置的路由表呈現帶有適當路由a
標記。 如果您還有其他參數要傳遞給查詢字符串,則也可以像在示例中使用another
參數一樣添加它。
切勿將邏輯放在視圖中。 該視圖應僅顯示模型中提供的信息。 將邏輯放在控制器中。
控制器:
[HttpGet]
public ActionResult Recipes(int cookId)
{
var recipes = /* get recipes based on cook */;
List<RecipeModel> model = recipes
.Select(r => new RecipeModel
{
Id = r.Id,
CookId = r.CookId,
...
})
.ToList();
return View(model);
}
視圖:
@model List<RecipeModel>
@foreach (RecipeModel item in Model)
{
<div>
<span>Id:</span>
<span>@item.Id</span>
</div>
}
控制器:
[HttpGet]
public ActionResult GetRecipes(int cookId)
{
// model can view a List<Recipe>, logic goes here
var model = SomeQueryThatReturnsRecipesFrom(cookId);
return View(model)
}
視圖(例如,views \\ yourController \\ GetRecipes.cshtml),僅使用此文件顯示數據,不建議在此處放置邏輯:
@model List<Namespace.Recipe>
<h2>Recipes</h2>
@foreach(var r in Model)
{
<p>r.Name</p>
}
這將通過以下查詢字符串調用:
/Recipes/GetRecipes?cookId=SomeId
您可能有一個CooksController。 該控制器將返回廚師列表。 該列表可能包含廚師食譜的鏈接。 您的RecipesController可以處理給定cookId的所有食譜的請求。
@Html.ActionLink("Recipes", "RecipesByCook", "Recipes", new { cookId = model.cookId }, null};
上面的代碼在Cooks / Index.shtml視圖中使用。 它創建一個鏈接,該鏈接使用查詢字符串來標識所需的cookId。
然后,RecipesController將具有RecipiesByCook方法,該方法采用cookId的參數。 此方法將處理對此類URL的請求,例如Home / Recipies / RecipeByCook?cookId = 4。
然后,您的RecipesController可以返回帶有要顯示的正確食譜集的ActionResult。 非常簡單(例如,您可能需要添加更多內容以顯示視圖,例如有關廚師的信息):
public ActionResult RecipesByCook(int cookId)
{
var recipes = repository.Recipes.Where(r => r.cookId == cookId);
return View(recipes);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.