简体   繁体   中英

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

Object reference not set to an instance of an object

This is my code: this method is in the PostRepository and get postGroup with Id from database:

    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 :

    [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:

    @{
        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 :

    @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:

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:

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:

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?

I changed EditPostGroup(PostGroup postGroup, IFormFile imgPostGroupUp) method to EditPostGroup(PostGroupViewModel postGroupViewModel, IFormFile imgPostGroupUp) ,but there is still a problem.

You can use a query string instead of passing the id in .net core:

[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:

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

Also, using # in the src of a file in razor view causes this problem. 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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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