ASP.NET Core 6 MVC - POST method not being hit when GET action method receives parameter

36 views Asked by At

Why is this not working?

In create GET, I am receiving an optional idEnt parameter.

If I call in browser MyController/Create/5, it shows view ok, and even client validation works ok, but on form submit, the POST action method in controller is not being hit... why?

(it does not throw any exception either, it just reloads the view)

Controller:

[Route("MyController/Create/{idEnt:int?}")]
public async Task<IActionResult> Create(int? idEnt) 
{
    MyEntity ent = db.Find(idEnt);

    var mod = new Mod() { idEnt = idEnt }

    return View(mod);
}

[HttpPost]
[ValidateAntiForgeryToken]
[WebTrail(AuditLevel = 3)]
public async Task<IActionResult> Create(Mod mod) 
{
    if (ModelState.IsValid) 
    {
        _db.Add(mod);
        await _db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(mod);
}

View:

@model My.Namespace.Mod
    <div>
        <form asp-action="Create">
            <input type="hidden" asp-for="Id" />
            <input type="hidden" asp-for="IdEnt" />

            <label asp-for="someField" class="control-label"></label>
            <input asp-for="someField" class="form-control" />
            <span asp-validation-for="someField" class="text-danger"></span>

            //more form inputs etc here

            <input type="submit" value="Save" class="btn btn-primary" />
        </form>
    </div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Model:

public class Mod 
{
    public int Id { get; set; }

    [ForeignKey("Ent")]
    public int? IdEnt { get; set; }

    [DisplayFormat(DataFormatString = "{0}€", NullDisplayText = "---")]
    [Column(TypeName = "decimal(15,2)")]
    public decimal? SomeField { get; set; }

    public virtual Ent Ent { get; set; }
}
0

There are 0 answers