Search code examples
c#asp.net-mvcrazor

An action method is created but it still gives the "Http 404 error of missing url"


I have created a form and a button SAVE. I have also created an action method CREATE which will be called when we click SAVE button. I want to see model binding now but when I fill in the form and click save button it shows following error message.it shows the error message See attached code please

@using (Html.BeginForm("Create", "Customer"))
            {
                <div class="form-group">
                    @Html.LabelFor(m=>m.Customer.Name)
                    @Html.TextBoxFor(m=>m.Customer.Name, new { @class="form-control"})
                </div>

                <div class="form-group">
                    @Html.LabelFor(m=>m.Customer.BirthDate)
                    @Html.TextBoxFor(m=>m.Customer.BirthDate, new { @class="form-control"})
                </div>

                <div class="checkbox">
                    <label>
                        @Html.CheckBoxFor(m=>m.Customer.IsSubscribedToNewsLetter) Subscribed to Newsletter?
                    </label>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m=>m.Customer.MembershipTypeId)
                   @*List of items*@
                    @Html.DropDownListFor(m=>m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes,"Id","Name"),"Select",new { @class="form-control"})
                </div>

                <button type="submit" class="btn btn-primary">Save</button>
}

Below is the Create action method from controller

 [HttpPost]
    public ActionResult Create(Customer customer)
    {
        return View();
    }

Solution

  • try to add an attribute route

    [Route("~/customer/create")]
    public ActionResult Create(Customer customer)
    

    and add a model to the top of the view

    @model Customer
    
    @using (Html.BeginForm("Create", "Customer", FormMethod.Post)) {
    

    and if you are using Net 4.8 or older you have to config attribute routing

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
     
        routes.MapMvcAttributeRoutes();
     
        routes.MapRoute(
            name: “Default”,
            url: “{controller}/{action}/{id}”,
            defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
        );
    }
    ````