Asp.net core mvc 在MVC中在视图之间传递参数
我有一个ASP.NET核心MVC web应用程序。我在Asp.net core mvc 在MVC中在视图之间传递参数,asp.net-core-mvc,Asp.net Core Mvc,我有一个ASP.NET核心MVC web应用程序。我在Index方法中有一个searchString参数。填充参数后,我可以在web链接上看到值,例如…?SearchString=202 我希望将此参数发送到第二个方法(例如,编辑),而不是在那里更改它,并在用户按下后退按钮后发送回索引方法。 这个想法是,当用户按下后退按钮时,他返回到Index视图,但他丢失了searchString参数,并且用户没有根据以前的搜索进行过滤的页面。如果要在索引编辑索引的路径中传递搜索字符串,您可以使用ViewBa
Index
方法中有一个searchString
参数。填充参数后,我可以在web链接上看到值,例如…?SearchString=202
我希望将此参数发送到第二个方法(例如,编辑
),而不是在那里更改它,并在用户按下后退按钮后发送回索引
方法。
这个想法是,当用户按下后退按钮时,他返回到
Index
视图,但他丢失了searchString
参数,并且用户没有根据以前的搜索进行过滤的页面。如果要在索引编辑索引的路径中传递搜索字符串,您可以使用ViewBag
,然后将其作为routevalue传递。下面是一个简单的工作演示:
索引操作,将搜索字符串保存在ViewBag.searchString
中
public async Task<IActionResult> Index(string searchString)
{
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
ViewBag.SearchString = searchString;
}
return View(await movies.ToListAsync());
}
编辑动作
公共异步任务编辑(int?id,string returnString=null)
{
if(id==null)
{
返回NotFound();
}
var movie=wait_context.movie.FindAsync(id);
ViewBag.SearchString=返回字符串;
如果(电影==null)
{
返回NotFound();
}
返回视图(电影);
}
编辑视图,反向链接
<div>
@if (ViewBag.SearchString != null)
{
<a asp-action="Index" asp-route-searchString="@ViewBag.SearchString">Back to List</a>
}
else
{
<a asp-action="Index">Back to List</a>
}
</div>
@if(ViewBag.SearchString!=null)
{
返回列表
}
其他的
{
返回列表
}
我没想到会有这么干净的代码。我喜欢学习正确的代码编写程序。非常感谢你的回答。
public async Task<IActionResult> Edit(int? id,string returnString = null)
{
if (id == null)
{
return NotFound();
}
var movie = await _context.Movie.FindAsync(id);
ViewBag.SearchString = returnString;
if (movie == null)
{
return NotFound();
}
return View(movie);
}
<div>
@if (ViewBag.SearchString != null)
{
<a asp-action="Index" asp-route-searchString="@ViewBag.SearchString">Back to List</a>
}
else
{
<a asp-action="Index">Back to List</a>
}
</div>