[英]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.