[英]c# asp.net core mvc passing data from view to controller and from controller back to view
I have a problem writing a simple app in asp.net.我在 asp.net 中编写一个简单的应用程序时遇到问题。 My idea is to pass data from that form to create a movie in my controller and then I want this controller (AddMovie) to sen this movie to my movieList and I want this to be shown in the view.我的想法是从该表单传递数据以在我的控制器中创建电影,然后我希望此控制器 (AddMovie) 将这部电影发送到我的电影列表中,并且我希望将其显示在视图中。 I tried some ways, but none worked.我尝试了一些方法,但没有一个奏效。 How can I do that?我怎样才能做到这一点?
View:看法:
@model IEnumerable<Movie>
@{
// ViewData["Title"] = "MovieView";
ViewBag.Title = "Welcome to My Page";
}
<h1>MoviesView</h1>
@foreach (var item in Model)
{
<div class="text-center">
<p>Id:item.Id </p>
<p>Name:item.Name</p>
<p>Author: item.Author</p>
</div>
<br />
}
<br />
<form asp-controller="MoviesController" method="post">
Id: <input type="text" name="movieId" /><br />
Name: <input type="text" name="movieName" /><br />
Author: <input type="text" name="movieAuthor" />
<input type="submit" value="Submit" formaction="AddMovie" />
</form>
<p>@ViewBag.Result</p>
Controller:控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebMVCAPP_L.Models;
namespace WebMVCAPP_L.Controllers
{
public class MoviesController : Controller
{
List<Movie> movieList = new List<Movie>();
public IActionResult Index()
{
return View(movieList);
}
[HttpPost]
public IActionResult AddMovie()
{
int id = Convert.ToInt32(HttpContext.Request.Form["movieId"].ToString());
string name = HttpContext.Request.Form["movieName"].ToString();
string author = HttpContext.Request.Form["movieAuthor"].ToString();
Movie movie = new Movie(id,name,author);
movieList.Add(movie);
return View("Index");
}
}
}
When you routing from one action to another action then you need to use tempdata.当您从一个操作路由到另一个操作时,您需要使用临时数据。
namespace WebMVCAPP_L.Controllers
{
public class MoviesController : Controller
{
List<Movie> movieList = new List<Movie>();
public IActionResult Index()
{
if(TempData["myData"]!=null){
movieList = JsonConvert.DeserializeObject<List<Movie>>((String)TempData["myData"]);
}
return View(movieList);
}
[HttpPost]
public IActionResult AddMovie()
{
int id = Convert.ToInt32(HttpContext.Request.Form["movieId"].ToString());
string name = HttpContext.Request.Form["movieName"].ToString();
string author = HttpContext.Request.Form["movieAuthor"].ToString();
Movie movie = new Movie(id,name,author);
movieList.Add(movie);
String str = JsonConvert.SerializeObject(movieList)
TempData["myData"] = str ;
return View("Index");
}
}
}
<form asp-action="AddMovie" asp-controller="Movies">
<input type="submit" />
</form>
Before anything else, you need some way of persisting your List<Movie>()
.首先,您需要某种方式来持久化您的List<Movie>()
。 HTTP, and therefore MVC, is stateless. HTTP 和 MVC 是无状态的。 Ideally you would be using a database, but you could use Session
for testing purposes:理想情况下,您将使用数据库,但您可以使用Session
进行测试:
List<Movie> movieList
{
get
{
if (Session["movieList"] == null)
{
Session["movieList"] = new List<Movie>();
}
return Session["movieList"] as List<Movie>;
}
}
Yo also need to add asp-action
to your form to post back to your AddMovie
method:您还需要将asp-action
添加到您的表单以回发到您的AddMovie
方法:
<form asp-controller="MoviesController" asp-action="AddMovie" method="post">
Then, change your method signature:然后,更改您的方法签名:
public IActionResult AddMovie(int id, string name, string author)
The MVC framework will automatically bind form fields to arguments of the same name. MVC 框架会自动将表单字段绑定到同名的参数。
Finally, return a HTTP redirect rather than the view itself:最后,返回 HTTP 重定向而不是视图本身:
[HttpPost]
public IActionResult AddMovie()
{
Movie movie = new Movie(id, name, author);
movieList.Add(movie);
return RedirectToAction("Index");
}
The browser will then perform a HTTP GET to your Index
method for the (persisted) movie list.然后,浏览器将对(持久化)电影列表的Index
方法执行 HTTP GET。
It shows me something like this An unhandled exception occurred while processing the request. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'System.Collections.Generic.List`1[WebMVCAPP_L.Models.Movie]'. Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer.Serialize(IDictionary<string, object> values)
它向我展示了这样的事情An unhandled exception occurred while processing the request. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'System.Collections.Generic.List`1[WebMVCAPP_L.Models.Movie]'. Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer.Serialize(IDictionary<string, object> values)
An unhandled exception occurred while processing the request. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'System.Collections.Generic.List`1[WebMVCAPP_L.Models.Movie]'. Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer.Serialize(IDictionary<string, object> values)
Stack Query Cookies Headers Routing
InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'System.Collections.Generic.List`1[WebMVCAPP_L.Models.Movie]'.
Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer.Serialize(IDictionary<string, object> values)
Microsoft.AspNetCore.Mvc.ViewFeatures.CookieTempDataProvider.SaveTempData(HttpContext context, IDictionary<string, object> values)
Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary.Save()
Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.SaveTempDataFilter.SaveTempData(IActionResult result, ITempDataDictionaryFactory factory, IList<IFilterMetadata> filters, HttpContext httpContext)
Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.SaveTempDataFilter.OnResultExecuted(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.