简体   繁体   English

当我从具有多个 forms 的视图提交表单时,为什么在我的 controller 中收到 null 值? 带 ASP.NET 内核 5 MVC

[英]Why do I receive null values in my controller when I submit a form from a view with multiple forms? With ASP.NET Core 5 MVC

I am developing a web application using ASP.NET Core 5 MVC, in which I seek to make multiple submissions of POST type forms to my controller from a view that receives an IEnumerable (from a model called Result ) with which I am filling in dynamically the values of the inputs of each form. I am developing a web application using ASP.NET Core 5 MVC, in which I seek to make multiple submissions of POST type forms to my controller from a view that receives an IEnumerable (from a model called Result ) with which I am filling in dynamically the values每种形式的输入。

However, when I send one of those forms from the view through the controller, in the controller I only receive an object from the model with all the null or empty values, which tells me that it seems that this data was never sent through the form to my controller. However, when I send one of those forms from the view through the controller, in the controller I only receive an object from the model with all the null or empty values, which tells me that it seems that this data was never sent through the form到我的 controller。

Is there a better way to accomplish this or how do I pass these values from multiple forms to my controller?有没有更好的方法来实现这一点,或者如何将这些值从多个 forms 传递到我的 controller? In advance an apology if what I am doing is already totally wrong, I have been learning ASP.NET Core MVC for a few days.如果我所做的已经完全错误,请提前道歉,我已经学习 ASP.NET Core MVC 几天了。

CONSIDERATIONS注意事项

What I seek to achieve is that the user can enter multiple values that belong to the same model in the same view, since each form although it is the same seeks to update a different record or column in the same model or table, so when the submit of the form is sent to the Controller the view does not change, and only the records in the database are updated with each submit in the view.我想要实现的是用户可以在同一个视图中输入属于同一个 model 的多个值,因为每个表单虽然是相同的,但它试图更新同一个 model 或表中的不同记录或列,所以当表单的提交被发送到 Controller 视图不会改变,只有数据库中的记录会随着视图中的每次提交而更新。 If there is a better way or correct way to do this, I am willing to change the logic, because as I mentioned, I have been using the Framework for little.如果有更好的方法或正确的方法可以做到这一点,我愿意改变逻辑,因为正如我所提到的,我已经很少使用框架了。

Explained the problem and my goal, I will explain in greater detail the flow and code mentioned:解释了问题和我的目标,我将更详细地解释所提到的流程和代码:

  1. From the Mechanical method of my controller, I return a list of Objects to their corresponding View, which are brought by a DataBaseContext :从我的 controller 的Mechanical方法中,我将一个对象列表返回到它们对应的视图,这些视图由DataBaseContext带来:

     // CONTROLLER() that passes an enumerable list of Objects to View Mechanical.cshtml public IActionResult Mechanical() { IEnumerable<Result> objList = _db.Results; return View(objList); }
  2. In the Mechanical() view, I get this list of objects and iterate over it through a forEach() loop, where for each object I create a form that directs to the same controller method called Update() , in which I get the values of the object in null and empty (that being my problem):Mechanical()视图中,我获取此对象列表并通过forEach()循环对其进行迭代,在该循环中,我为每个 object 创建了一个表单,该表单指向名为Update()的相同 controller 方法,其中我得到了值null 中的 object 和空(这是我的问题):

// VIEW
@model IEnumerable<FatForm.Models.Result>

@if (Model.Count() > 0)
{
    @foreach(var result in Model)
    {
        <form method="post" asp-action="Update">
            <input asp-for="@result.Id" hidden />
            <input asp-for="@result.Type" hidden />
            <input asp-for="@result.FatId" hidden />
            <div class="border p-3">
                <div class="form-group row">
                    <h2 class="text-black-50 pl-3">Edit Result</h2>
                </div>
                <div class="row">
                    <div class="col-12">
                        <div class="form-group row">
                            <div class="col-3">
                                <label asp-for="@result.Section"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@result.Procedure"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@result.ResultDescription"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@result.Passed"></label>
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-3">
                                <input asp-for="@result.Section" class="form-control" />
                            </div>
                            <div class="col-3">
                                <input asp-for="@result.Procedure" class="form-control" />
                            </div>
                            <div class="col-3">
                                <input asp-for="@result.ResultDescription" class="form-control" />
                                <span asp-validation-for="@result.ResultDescription" class="text-danger"></span>
                            </div>
                            <div class="col-3">
                                <input asp-for="@result.Passed" class="form-control" />
                                <span asp-validation-for="@result.Passed" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-8 offset-2 row">
                                <div class="col">
                                    <input type="submit" class="btn btn-info w-75" value="Save" />
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </form>        
    }
}
else
{
    <p>No results created yet</p>
}

@section Scripts{
    @{
        <partial name="_ValidationScriptsPartial" />
    }
}
  1. I'm supposed to be looking to send the form values to the following Update() controller method, in which I get all the object values to null:我应该希望将表单值发送到以下Update() controller 方法,其中我将所有 object 值发送到 null:

     // POST Update [HttpPost] [ValidateAntiForgeryToken] public IActionResult Update(Result obj) { if (ModelState.IsValid) { _db.Results.Update(obj); _db.SaveChanges(); //return RedirectToAction("Index"); } return View(obj); }

在这里您可以从视图中看到控制器上的空值

As I explained at the beginning, I hope can help me by indicating what I am doing wrong or in what way I should do it.正如我在开头所解释的那样,我希望可以通过指出我做错了什么或应该以什么方式来帮助我。 Thanks in advance for your help.在此先感谢您的帮助。

Here you need to add FromBody attribute in your action method parameter.在这里,您需要在您的操作方法参数中添加 FromBody 属性。

public IActionResult Update([FromBody]Result obj)
{
   .....
}

Model binding looks through the sources for the name pattern prefix.property_name . Model 绑定在源中查找名称模式prefix.property_name If nothing is found, it looks for just property_name without the prefix.In your code,the asp-for tag helper will generate the name like: result.propertyName .It could not match with backend model.如果没有找到,它只查找不带前缀的property_name 。在您的代码中, asp-for标签助手将生成如下名称: result.propertyName 。它无法与后端 model 匹配。 You need use [Bind(Prefix ="result")] to specify the prefix:您需要使用[Bind(Prefix ="result")]来指定前缀:

[HttpPost]
[ValidateAntiForgeryToken]

public IActionResult Update([Bind(Prefix ="result")]Result obj)
{
    //do your stuff...
}

As for receive IEnumerable parameter in action, firstly you need change your razor view to move the form outside the foreach loop, then you need change the asp-for tag helper tattribute to @Model.ToList()[index].PropertyName :至于接收IEnumerable参数,首先您需要更改您的 razor 视图以将表单移到 foreach 循环之外,然后您需要将 asp-for 标签助手属性更改为@Model.ToList()[index].PropertyName

@model IEnumerable<Result>

@if (Model.Count() > 0)
{
    <form method="post" asp-action="Update">
        @for (int i = 0; i < Model.Count(); i++)
        {
            <input asp-for="@Model.ToList()[i].Id" hidden />
            <input asp-for="@Model.ToList()[i].Type" hidden />
            <input asp-for="@Model.ToList()[i].FatId" hidden />
            <div class="border p-3">
                <div class="form-group row">
                    <h2 class="text-black-50 pl-3">Edit Result</h2>
                </div>
                <div class="row">
                    <div class="col-12">
                        <div class="form-group row">
                            <div class="col-3">
                                <label asp-for="@Model.ToList()[i].Section"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@Model.ToList()[i].Procedure"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@Model.ToList()[i].ResultDescription"></label>
                            </div>
                            <div class="col-3">
                                <label asp-for="@Model.ToList()[i].Passed"></label>
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-3">
                                <input asp-for="@Model.ToList()[i].Section" class="form-control" />
                            </div>
                            <div class="col-3">
                                <input asp-for="@Model.ToList()[i].Procedure" class="form-control" />
                            </div>
                            <div class="col-3">
                                <input asp-for="@Model.ToList()[i].ResultDescription" class="form-control" />
                                <span asp-validation-for="@Model.ToList()[i].ResultDescription" class="text-danger"></span>
                            </div>
                            <div class="col-3">
                                <input asp-for="@Model.ToList()[i].Passed" class="form-control" />
                                <span asp-validation-for="@Model.ToList()[i].Passed" class="text-danger"></span>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        }
        <div class="form-group row">
            <div class="col-8 offset-2 row">
                <div class="col">
                    <input type="submit" class="btn btn-info w-75" value="Save" />
                </div>
            </div>
        </div>
    </form>
}
else
{
<p>No results created yet</p>
}

Controller: Controller:

[HttpPost]
[ValidateAntiForgeryToken]

public IActionResult Update(IEnumerable<Result> obj)
{
    return View("Mechanical", obj);
}

Result:结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MVC ASP.NET提交给Controller时在View中获取ViewData.Model - MVC ASP.NET Getting back my ViewData.Model in my View when I submit to a Controller 当我模拟ASP.NET MVC控制器时,我的ActionMethod不返回任何视图。 为什么? - When I mock my ASP.NET MVC controller, my ActionMethod returns no view. Why? 在ASP.NET MVC中将多种表单从视图传递到控制器 - Passing multiple forms from View to Controller in ASP.NET MVC ASP.NET Core 3.0 WebAPI - 为什么在控制器方法中处理异常时我仍然收到 InternalServerError? - ASP.NET Core 3.0 WebAPI - why do I still receive InternalServerError when exception is handled in the Controller Method? 如何在ASP.NET MVC中将表单提交到数据库中 - How do I submit a form into a database in asp.net MVC 如何从 ASP.NET Core 6 MVC EF 中的 controller 中的另一个 controller 实例化服务? - How do I instantiate a service from another controller in a controller in ASP.NET Core 6 MVC EF? 我如何告诉 MVC 中间件我的 class 是 ASP.NET Core 中的一个 Controller? - How do I tell the MVC middleware that my class is a Controller in ASP.NET Core? 为什么当我不使用ConfigureHttps时,asp.net core 2.1 MVC中的TempData为null? - why when I don't use ConfigureHttps, TempData is null in asp.net core 2.1 MVC? Angular和ASP.NET MVC-当我将参数传递给后端控制器时参数为null - Angular & ASP.NET MVC - Parameter is null when I pass a parameter to my backend Controller ASP.NET MVC - 如何从视图中调用 Controller 方法以重定向到多个其他视图? - ASP.NET MVC - How do I Call a Controller Method from within a View to Redirect to Multiple Other Views?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM