简体   繁体   English

为什么 Controller 'Get' Edit 方法在 ASP.NET Core 6 MVC 中被调用两次?

[英]Why does Controller 'Get' Edit method getting called twice in ASP.NET Core 6 MVC?

I have problem in edit view.我在编辑视图中遇到问题。 When I debug my code, after Id is passed from ShowCategory view to EditPostGroup method in controller, it works correctly, but after page loads, Id zero is sent to the Edit method in controller and throws an error当我调试我的代码时,在IdShowCategory视图传递到 controller 中的EditPostGroup方法后,它工作正常,但在页面加载后, Id零被发送到 controller 中的 Edit 方法并抛出错误

Object reference not set to an instance of an object Object 引用未设置为 object 的实例

This is my code: this method is in the PostRepository and get postGroup with Id from database:这是我的代码:此方法在PostRepository中并从数据库中获取带有IdpostGroup

    public PostGroupViewModel GetPostGroupById(int postGroupId)
    {
        var postGroup = _context.PostGroups.Find(postGroupId);

        PostGroupViewModel postGroupViewModel = new PostGroupViewModel()
        {
             GroupId = postGroup.GroupId,
             GroupTitle = postGroup.GroupTitle,
             GroupImageName = postGroup.GroupImageName,
             IsDelete =  postGroup.IsDelete,
             ParentId = postGroup.ParentId
        };

        return postGroupViewModel;
    }

These are Get and Post edit method in CategoryController :这些是CategoryController中的GetPost编辑方法:

    [HttpGet]
    public IActionResult EditPostGroup(int id)
    {
        var groups = _postService.GetGroupForManagePost();
        ViewData["Groups"] = new SelectList(groups, "Value", "Text");
        var postGroupViewModel = _postService.GetPostGroupById(id);
        return View(postGroupViewModel);
    }

    [HttpPost]
    public IActionResult EditPostGroup(PostGroup postGroup, IFormFile imgPostGroupUp)
    {
        if (!ModelState.IsValid)
            return View("EditPostGroup");

        _postService.UpdatePostGroup(postGroup, imgPostGroupUp);

        return RedirectToAction("ShowCategory", "Category");
    }

This is 'ShowCategory' View, It sends PostGroupId to Edit action method:这是“ShowCategory”视图,它将 PostGroupId 发送到 Edit 操作方法:

    @{
        ViewData["Title"] = "Category List";
       
    }
    
    <div class="row">
        <div class="col-lg-12">
            <h4 style="color:darkblue;" >Category List</h4>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
            
                <div class="panel-body">
                    <br />
                
                    <div class="col-md-12" style="margin: 10px 0;">   
                        <a asp-controller="Category" asp-action="CreateCategory" asp-area="Admin" class="btn btn-outline btn-success">Create Category</a>               
                    </div>
                    <br />
                    <br />
                    <br />
                    <table class="table table-striped table-bordered table-hover dataTable no-footer text-center" id="dataTables-example" aria-describedby="dataTables-example_info">
                        <thead class="table-success black-ribon">
                            <tr>
                              
                                <th>Title</th>
                                <th>Parent Category</th>
                                <th>Image</th>
                                <th>Operations</th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach (var item in  @ViewBag.CategoryList)
                        {
                            <tr>
                          
                                <td>
                                    @item.GroupTitle
                                </td>
                                <td>
                                    @item.ParentId
                                </td>
                                <td>
                                    <img class="thumbnail" style="width:40px;height:40px;"  src="/img/postGroup/@item.GroupTitle/@item.GroupImageName" alt="">
                                </td>
    
                                <td>
                                    <a href="/Admin/Category/EditPostGroup/@item.GroupId" class="btn btn-primary btn-md">
                                        Edit
                                    </a>
                                </td>
                            </tr>
                        }
                        </tbody>
                    </table>
    
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>

This is the EditPostGroupView :这是EditPostGroupView

    @model DataLayer.Models.ViewModels.PostGroup.PostGroupViewModel
    @{
        ViewData["Title"] = "Post Edit";
        //Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
    }
    
    <div class="row">
        <form method="post" asp-action="EditPostGroup" enctype="multipart/form-data">
            @* <input type="hidden" asp-for="GroupId" />*@
            @*<input type="hidden" asp-for="Post.PostImageName"/>*@
      
            <div class="col-md-8">
                <h2>Category List</h2>
                <hr/>
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" asp-for="GroupTitle" class="form-control">
                    <span asp-validation-for="GroupTitle"></span>
                </div>
                <div class="form-group">
                    <label>ParentId</label>
                    <select class="form-control" asp-for="ParentId" asp-items="@(ViewData["Groups"] as SelectList)">
                    <option value="">-- please select --</option>
                    </select>
                    <span asp-validation-for="ParentId"></span>
                </div>
            </div>
            <div class="col-md-4">
                <p></p>
                <img id="imgPost" class="thumbnail" src="img/postGroup/@Model.GroupTitle/@Model.GroupImageName"/>
                <div class="form-group">
                    <label>Select Image</label>
                    <input type="file" name="imgPostGroupUp" id="imgPostGroupUp">
                </div> 
            </div> 
            <input type="submit" value="Edit" class="btn btn-success"/>
        </form>
    </div>
        
    @section scripts
        {
        <script>    
            function readURL(input) {   
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
    
                    reader.onload = function (e) {
                        $('#imgPost').attr('src', e.target.result);
                    }
    
                    reader.readAsDataURL(input.files[0]);
                }
            }
    
            $("#imgPostUp").change(function () {
                readURL(this);
            });
        </script>         
    }

This is the Routing in Program.cs:这是 Program.cs 中的路由:

app.MapControllerRoute(
    name: "MyArea",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

This is PostGroup Model:这是邮政组 Model:

public class PostGroup
    {
        [Key]
        public int GroupId { get; set; }
        //public int? SubGroupId { get; set; }

        public string GroupTitle { get; set; }

        [MaxLength(50)]
        public string? GroupImageName { get; set; }

        public bool IsDelete { get; set; }

        [Display(Name = "Category")]
        public int? ParentId { get; set; }

        [ForeignKey("ParentId")]
        public  List<PostGroup>? PostGroups { get; set; }

        [InverseProperty("PostGroup")]
        //[NotMapped]
        public  List<Post>? Posts { get; set; }
}

This is postGroupViewModel:这是 postGroupViewModel:

public class PostGroupViewModel
    {
        public int GroupId { get; set; }
  
        public string GroupTitle { get; set; }

        [MaxLength(50)]
        public string? GroupImageName { get; set; }

        public bool IsDelete { get; set; }

        public int? ParentId { get; set; }
    }

What is the problem?问题是什么?

Could it be a problem with the Program.cs and middleware? Program.cs和中间件有问题吗?

I changed EditPostGroup(PostGroup postGroup, IFormFile imgPostGroupUp) method to EditPostGroup(PostGroupViewModel postGroupViewModel, IFormFile imgPostGroupUp) ,but there is still a problem.我将EditPostGroup(PostGroup postGroup, IFormFile imgPostGroupUp)方法更改为EditPostGroup(PostGroupViewModel postGroupViewModel, IFormFile imgPostGroupUp) ,但仍然存在问题。

You can use a query string instead of passing the id in .net core:您可以使用查询字符串而不是在 .net 核心中传递 id:

[HttpGet]
    public async Task<IActionResult> Edit()
    {
        string id = HttpContext.Request.Query["id"].ToString();
        var model = await _service.FindAsync(int.Parse(id));
        return View(model);
    }

in razor view:在 razor 查看:

<a href="/service/edit?id=@item.ServiceId">

Also, using # in the src of a file in razor view causes this problem.此外,在 razor 视图中的文件的 src 中使用 # 会导致此问题。 remove it or give it a value.删除它或给它一个值。

<img id="img-master" class="thumbnail" src="#" />

to

<img id="img-master" class="thumbnail" src="/images/@Model.ImageEdit" />

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

相关问题 ASP.NET Core MVC添加的Edit()动作方法(POST)脚手架为什么ID参数传了两次? - Why is the ID parameter passed twice in the Edit() action method (POST) scaffold added by ASP.NET Core MVC? ASP.Net核心有时会动作控制器被调用两次 - ASP.Net core sometimes the action controller is called twice "ASP.NET Web App CORE:未调用控制器中的 HttpPost 编辑方法" - ASP.NET Web App CORE: the HttpPost Edit Method in Controller not being called 在这种情况下如何创建 Edit 方法? ASP.NET 核心 MVC - How to create an Edit method in this situation? ASP.NET Core MVC Why Fetch Post request with JSON parameter in the body to ASP.NET Core 3.1 WEB API or MVC Controller does not get anything? - Why Fetch Post request with JSON parameter in the body to ASP.NET Core 3.1 WEB API or MVC Controller does not get anything? .NET Core 1.1 MVC控制器方法未调用 - .NET Core 1.1 MVC Controller method not getting called 获取在ASP.NET MVC中调用控制器的视图的名称 - Get the name of view who called controller in ASP.NET MVC ASP.Net MVC中的GET方法未从Javascript单击按钮时被调用 - GET Method in ASP.Net MVC is not getting called on button click from Javascript ASP.NET Core:Modal 不会将值传递给控制器​​方法 - ASP.NET Core: Modal does not pass values to controller method ASP.NET MVC 4-仅调用一种POST方法的Web API不会被调用 - ASP.NET MVC 4 - Web API with only one POST method does not get called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM