Zvone Pandza
Zvone Pandza

Reputation: 20

Passing value from form tag to an action method not working

I have a form with input type number and I want to select one number, press Submit and Delete specific row from my database.

The input type looks like this:

<input type="number" name="id" value=""/>  

I'm working with paths and I want to pass that specific value to:

"http://localhost:51206/api/Values/delete/id"

It works when I put some number instead of id. When I press Submit with id value, it says it doesn't work because it is null value.

Html

<form action="http://localhost:51206/api/Values/delete/id" method="post">
    <fieldset>
        <div style="text-align: center">
            DELETE
            <input type="number" name="id" value=""/>
            <input type="submit" value="Submit"/>
        </div>
    </fieldset>
</form>  

Controller

public IHttpActionResult Delete(int id)
    {
        var delete = Connection.dm.Student.FirstOrDefault(s => s.StudentID == id);
        if (delete != null) {
            Connection.dm.Student.Remove(delete);
            Connection.dm.SaveChanges();
        }
        return Ok(Models.db.test);
    }

Upvotes: 0

Views: 1400

Answers (2)

Sahil Sharma
Sahil Sharma

Reputation: 1899

Drop the '/id' from url, simplify it and use id attribute in your text box and it will bind.

View

<form action="api/Values/Delete" method="post">
    <fieldset>
        <div style="text-align: center">
            DELETE
            <input type="number" id="id" value=""/>
            <input type="submit" value="Submit"/>
        </div>
    </fieldset>
</form> 

Controller

[HttpPost]
public IHttpActionResult Delete(int id)
{
  var delete = Connection.dm.Student.FirstOrDefault(s => s.StudentID == id);
  if (delete != null) {
      Connection.dm.Student.Remove(delete);
      Connection.dm.SaveChanges();
      }
      return Ok(Models.db.test);
}

Upvotes: 2

j03p
j03p

Reputation: 341

You should add attribute [HttpPost] to your method:

[HttpPost]
public IHttpActionResult Delete(int id)

and remove id from form action:

<form action="http://localhost:51206/api/Values/delete" method="post">

Upvotes: 1

Related Questions