Karthikeyan
Karthikeyan

Reputation: 173

MVC Action not firing

Controller :

public ActionResult Insert()
{
    return View();
}
public ActionResult Insert(Employee emp)
{
    Employee emp1 = new Employee();
    emp1.insert(emp);
    return View();
}

cshtml

@using (Html.BeginForm("Employee", "Insert", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.name)
    @Html.TextBoxFor(model => model.Email)
    @Html.TextBoxFor(model => model.mob)

    <input type="button" value="Register me" />
}

I have to save my model values on button click ('Register me'). Thanks in advance.

Upvotes: 0

Views: 1506

Answers (2)

Roman
Roman

Reputation: 12171

Try to set attributes in your controller:

[HttpGet] // here ([HttpGet] is default so here you can delete this attribute)
public ActionResult Insert()
{
    return View();
}

[HttpPost]  // here
public ActionResult Insert(Employee emp)
{
    Employee emp1 = new Employee();
    emp1.insert(emp);
    return View();
}

To call some action you need to submit your form. Change your button to submit type:

<input type="submit" value="Register me" /> // type="button" -> type="submit"

Also, in BeginForm you should firstly specify action name and then controller name:

@using (Html.BeginForm("Insert", "Employee", FormMethod.Post))

Upvotes: 7

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Its Because you have not declared HTTP POST on INSERT action

   [HttpPost]
   public ActionResult Insert(Employee emp)
    {
        Employee emp1 = new Employee();
        emp1.insert(emp);
        return View();
    }

When you are using Beginform and your FormMethod is Post the related Action needs to have same kind of HTTP, By the way it doesn't matter if you have [HttpGet] on first ActionResult Because in MVC, any ActionResult that haven't declared any type of HTTP request/respond are known as [HttpGet]

Also in your BeginForm():

@using (Html.BeginForm("ActionName(Insert)", "ControllerName", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.name)
    @Html.TextBoxFor(model => model.Email)
    @Html.TextBoxFor(model => model.mob)

    <input type="submit" value="Register me" />
}

Upvotes: 3

Related Questions