一般来说,我是 ASP.Net MVC 和 MVC 架构的新手。我正在使用 Database Code First 方法构建一个简单的应用程序。
我有一个带有名为的属性的食谱模型,cookId
它是创建食谱的用户的 ID。
现在,我希望能够将查询字符串传递到我的页面,并仅获取 cookId 与参数相同的食谱并在我的视图中列出 i。
我怎样才能做到这一点?我应该把这个逻辑放在哪里?在我的controller
还是在我的view
?
一般来说,我是 ASP.Net MVC 和 MVC 架构的新手。我正在使用 Database Code First 方法构建一个简单的应用程序。
我有一个带有名为的属性的食谱模型,cookId
它是创建食谱的用户的 ID。
现在,我希望能够将查询字符串传递到我的页面,并仅获取 cookId 与参数相同的食谱并在我的视图中列出 i。
我怎样才能做到这一点?我应该把这个逻辑放在哪里?在我的controller
还是在我的view
?
好吧,asp.net mvc 与路由或 TableRoutes 一起使用。默认路由使用以下格式创建:{controller}/{action}/{id}
.
因此,当您收到有关您的操作的请求时,您可以从id
您的操作(在控制器上)的参数中检索此 ID,并使用此值访问您的数据库并获取您需要在视图上显示的所有记录。你可以尝试这样的事情:
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 中不是一个好习惯。您可以在操作中使用参数并使用它。
在您的视图中,您可以使用 键入它并将其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
,例如在您的视图中:
@Html.ActionLink("Text of You Link", "Action", "Controller", new { id = 5, another = 10 }, new { @class = "css class for you link" });
并且 asp.net mvc 将a
在 global.asax 上设置的路由表之后呈现具有专用路由的标签。如果您有其他参数要传入查询字符串,您也可以像我在带有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);
}