ASP.NET 核心 MVC:实现保存和新建功能

ASP.NET Core MVC : Implement Save and New functionality

我正在尝试创建“保存”、'Save and new' 和 'Cancel' 功能。

据我了解,如果按钮的值为 'Save',我应该获取按钮值并保存,如果按钮值为 [,则保存并 return 创建操作=35=].

这是我的代码现在的样子:

型号

    [Key]
    public int Id { get; set; }
    
    [Required]
    public string Profile { get; set; }

查看

    <form asp-action="CreatePost">
        <div class="row g-3">
            <div class="form-group col-sm-6">
                <label asp-for="Profile" class="control-label"></label>
                <input asp-for="Profile" class="form-control" />
                <span asp-validation-for="Profile" class="text-danger"></span>
            </div>
        </div>
        <div class="d-flex flex-row justify-content-center">
            <button type="submit" value="Save" class="w-25 btn btn-primary btn-lg me-5">Save</button>
            <button type="submit" value="SaveNew" class="w-25 btn btn-primary btn-lg me-5">Save+New</button>
            <a class="w-25 btn btn-secondary btn-lg me-5" asp-action="Index">Cancel</a>
        </div>
    </form>

控制器

    [HttpPost]
    public IActionResult CreatePost(Profile obj)
    {
        _db.UserProfiles.Add(obj);
        _db.SaveChanges();
        return RedirectToAction("Index")            
    }

在浏览论坛数小时后,我想出了如何做到这一点。我不得不在视图和控制器中进行修改。这是我上面的答案的解决方案。

我修改了视图中的表单。必须先更改并分配按钮的名称和值。

查看:

<form asp-action="CreatePost">
        <div class="row g-3">
            <div class="form-group col-sm-6">
                <label asp-for="Profile" class="control-label"></label>
                <input asp-for="Profile" class="form-control" />
                <span asp-validation-for="Profile" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group d-flex flex-sm-shrink-1 justify-content-center">
            <button type="submit" name="ActionType" value="Save" class="btn btn-primary">Save</button>
            <button type="submit" name="ActionType" value="SaveNew" class="btn btn-primary mx-3">Save+New</button>
            <a class="btn btn-secondary" asp-action="Index">Cancel</a>
        </div>
</form>

然后我不得不修改控制器并设置一个if语句如下:

控制器

        [HttpPost]
        public IActionResult CreatePost(Profile obj, string ActionType)
        {
            if (ModelState.IsValid)
            {
                if (ActionType == "SaveNew")
                {
                    _db.Profiles.Add(obj);
                    _db.SaveChanges();
                    return RedirectToAction("Create");
                }
                else if (ActionType == "Save")
                {
                    _db.Profiles.Add(obj);
                    _db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            return View("Create",obj);

        }

因此,对应于每个按钮值,控制器将导航到适当的操作。如果您觉得这有帮助,请告诉我。