简体   繁体   English

模型绑定Null异常在Razor页面中为View组件

[英]Model Binding Null exception a View Component in Razor Pages

I use Asp.net core 2.1 and create View Component: 我使用Asp.net core 2.1并创建View Component:

public class UploadFileViewComponent:ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(IFormFile formFile)
    {

        return await Task.FromResult((IViewComponentResult) View("Default", formFile));
    }
}

and try to use this in razorpage: 并尝试在razorpage中使用它:

@page
@using Mi24.Core.ViewMolde
@model Mi24.Web.Pages.Admin.Users.CreateUserModel
@{
   ViewData["Title"] = "Title"
}

    @await Component.InvokeAsync("UploadFile",new{ formFile=Model.CreateUserViewModel.AvatarFile });

but get error: NullReferenceException: Object reference not set to an instance of an object. 但得到错误:NullReferenceException:对象引用未设置为对象的实例。

by adding this code to RazorPage above error solved: 通过将此代码添加到RazorPage上面的错误已解决:

[BindProperty]
    public CreateUserViewModel CreateUserViewModel { get; set; }

    public async Task OnGetAsync()
    {
        CreateUserViewModel=new CreateUserViewModel();
    }

on viewcomponent user select an images and by submit form OnPost method of razorpage fired but a catnt access to postedfile in Onpost: 在viewcomponent用户上选择一个图像,并通过提交razorpage的OnPost方法,触发了Onpost方法,但是对Onpost中的postfile进行了访问:

public async void OnPostAsync()
    {
      string fileName=  CreateUserViewModel.AvatarFile.FileName;
    }

this error: System.NullReferenceException 此错误:System.NullReferenceException

Here is the part of the code in the demo I made ,check the difference 这是我制作的演示中的代码部分,请检查其中的区别

CreateUserViewModel.cs CreateUserViewModel.cs

 public class CreateUserViewModel
{
    public Microsoft.AspNetCore.Http.IFormFile AvatarFile { get; set; }
}

Note that the type of AvatarFile in CreateUserViewModel.cs must be consistent with the type of the object arguments in the InvokeAsync method of UploadFileViewComponent. 请注意,CreateUserViewModel.cs中AvatarFile的类型必须与UploadFileViewComponent的InvokeAsync方法中的对象参数的类型一致。

Default.cshtml of the UploadFileViewComponent.cs UploadFileViewComponent.cs的Default.cshtml

@model RazorPage2_1Project.Models.CreateUserViewModel

<h2> Upload File</h2>

<form method="post" enctype="multipart/form-data" >
<div class="form-group">
    <div class="col-md-10">
        <input type="file" name="AvatarFile" asp-for="AvatarFile"/>
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>
</form>

Note : the value of asp-for and the name attribute of the input should be the same to what you want get in the post method . 注意: asp-for的值和输入的name属性应与您希望在post方法中获得的相同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM