I am trying to create 'Save, 'Save and new' and 'Cancel' functionality.
As my understanding goes, I, am supposed to get the button value and save if the value for the button is 'Save' and save and return to create action if the button value is 'SaveNew'.
This is how my code looks right now:
Model
[Key]
public int Id { get; set; }
[Required]
public string Profile { get; set; }
View
<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>
Controller
[HttpPost]
public IActionResult CreatePost(Profile obj)
{
_db.UserProfiles.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index")
}
CodePudding user response:
After hours of skimming through forums, I was able to make an idea of how this has to be done. I had to make modifications in both the View and Controller. Here is the solution to my answer above.
I modified the form inside the view. Had to change and assign and name and value to the button first.
View:
<form asp-action="CreatePost">
<div >
<div >
<label asp-for="Profile" ></label>
<input asp-for="Profile" />
<span asp-validation-for="Profile" ></span>
</div>
</div>
<div >
<button type="submit" name="ActionType" value="Save" >Save</button>
<button type="submit" name="ActionType" value="SaveNew" >Save New</button>
<a asp-action="Index">Cancel</a>
</div>
</form>
Then I had to modify the controller and set up an if statement as follows:
Controller
[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);
}
Hence, corresponding to each button value, the controller will navigate to appropriate action. Let me know if you found this helpful.