简体   繁体   English

c# asp.net core mvc 将数据从视图传递到控制器并从控制器返回到视图

[英]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" /> &nbsp;&nbsp;&nbsp;

</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.

相关问题 ASP.NET 核心 MVC - 将 Model 数据从视图传递回 Controller - ASP.NET Core MVC - Passing Model Data Back to Controller from View ASP.NET MVC C#:将视图数据传递给 controller - ASP.NET MVC C# : passing view data to controller 在 C# ASP.NET Core MVC 中使用 AJAX 将数据从视图传递到控制器 - Pass data from view to controller using AJAX in C# ASP.NET Core MVC 将数据从控制器传递到ASP.NET MVC中的视图 - Passing data from a controller to the view in ASP.NET MVC 在ASP.NET MVC中将数据从视图传递到控制器失败 - Passing Data from View to Controller failed in asp.net mvc ASP.NET MVC 3 Razor:将数据从视图传递到控制器 - ASP.NET MVC 3 Razor: Passing Data from View to Controller ASP.NET Core MVC:编辑用户,将数据从视图传递到 controller 时出现问题,身份 - ASP.NET Core MVC : edit user, problem with passing data from view to controller ,identity mvc 4 asp.net c# 将布尔值从控制器传递到视图 - mvc 4 asp.net c# passing boolean value from controller to view ASP.NET MVC-使用C#将引用不同程序集的模型从控制器传递到视图 - ASP.NET MVC - Passing a Model referencing a different assembly from a Controller to a View using C# 将两个或多个参数从 model 视图传递到 EF Core / ASP.NET Core MVC 应用程序中的 controller - Passing two or more parameters from model view to controller in EF Core / ASP.NET Core MVC application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM