Serge P.
Serge P.

Reputation: 327

Update and ASP.NET MVC model on button click

I'm new to ASP.NET MVC. I'm trying to update model on button click with no success: every time I push the button an HttpGet controller method is invoked.

Here is my markup

@model DataInterface.Model.Entry

<button onclick="location.href='@Url.Action("Survey")'">Finish survey</button>

Here is Controller code

[HttpGet]
public ActionResult Survey()
{
    var entry = new Entry();
    return View(entry);
}

[HttpPost]
public ActionResult Survey(Entry newEntry)
{
       // save newEntry to database
}

When I click button HttpGet method is invoked. Why?


It is bad to be a rookie) Thanks to all!

Upvotes: 1

Views: 15030

Answers (3)

WeSt
WeSt

Reputation: 2684

If you access a URL without explicitly specifying the HTTP method, ASP.NET MVC will assume a GET request. To change this, you can add a form and send it:

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    <input type="submit" value="Finish survey" />    
}

If you do this, your POST method will be invoked. The Entry parameter, however, will be empty, since you do not specify any values to send along with the request. The easiest way to do so is by specifying input fields, e.g. text inputs, dropdown, checkboxes etc.

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.Title)
    <input type="submit" value="Finish survey" />    
}

If you have the object stored on the server somewhere and only want to finish it off by writing it into the database or changing its status, you could pass the Id of the object (or some temporary Id) along the post request and make the controller method work only with the Id:

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    @Html.HiddenFor(m => m.Id)
    <input type="submit" value="Finish survey" />    
}

[HttpPost]
public ActionResult Survey(Entry newEntry)
{
    // newEntry.Id will be set here
}

Upvotes: 2

King
King

Reputation: 1

you must declare your form

@model DataInterface.Model.Entry
@using (Html.BeginForm("action", "Controlleur", FormMethod.Post, new {@class = "form", id = "RequestForm" }))
{
<input  type="submit" value="Finish survey" />
}

Upvotes: 0

speti43
speti43

Reputation: 3046

   @using (Html.BeginForm("Survey", "<ControllerName>", FormMethod.Post))
   {
       <input  type="submit" value="Finish survey" />    
   }

Upvotes: 0

Related Questions