我试图创建‘保存,’保存和新‘和’取消‘功能。
根据我的理解,我应该得到按钮值,如果按钮的值是“save”,则保存,如果按钮值为“SaveNew”,则返回创建操作。
现在我的代码就是这样的:
模型
[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")
}发布于 2021-10-31 11:23:06
在论坛上浏览了几个小时之后,我想出了一个如何去做的想法。我必须对视图和控制器进行修改。以下是我上述答案的解决办法。
我修改了视图中的表单。必须首先更改和分配按钮的名称和值。
视图:
<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);
}因此,对应于每个按钮值,控制器将导航到适当的操作。如果你觉得这有用的话请告诉我。
https://stackoverflow.com/questions/69778145
复制相似问题