Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button Event in ASP.NET MVC

Tags:

asp.net-mvc

I have created view page in MVC like

<%using (Html.BeginForm())
{ %>
    <%=LabelHelpers.Label("firstname", "FirstName:")%>
    <br/>
    <%=Html.TextBox("firstname")%>
    <br/><br/>
    <%=LabelHelpers.Label("lastname", "Lastname:")%>
    <br/>
    <%=Html.TextBox("lastname")%>
    <br/><br/>
    <input type="Button" value="Register"/>
<%} %>

Here I want to write Buttonclick Event ...How and Where should i write?

like image 872
Domnic Avatar asked Jan 18 '11 10:01

Domnic


1 Answers

Your input is of type button - these don't do anything without additional client side code.

If you want to handle the 'event' on the server in a similar way that you would have in ASP.NET, you should convert it to a submit button. Assuming your controller is called 'Account' and your action is called 'Register' your current code would look something like this:

public ViewResult Register()
{
    return View();
}

You want to start by passing a model to the view:

public ViewResult Register()
{
    var registerModel = new RegisterModel();

    return View(registerModel);
}

Your current view is using loosely typed inputs. Since you're passing it a model you can use strongly typed views. Your model should look something like this:

public class RegisterMode
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
}

To use strongly typed views, change your view to look like this:

<%using (Html.BeginForm())
{ %>
    <%=Html.LabelFor(x => x.Firstname)%>
    <br/>
    <%=Html.TextBoxFor(x => x.Firstname)%>
    <br/><br/>
    <%=Html.LabelFor(x => x.Surname)%>
    <br/>
    <%=Html.TextBoxFor(x => x.Surname)%>
    <br/><br/>
    <input type="submit" value="Register"/>
<%} %>

What we've done is told the view to build labels and text boxes for your RegisterModel type. This will allow the model values to be automatically mapped when you POST the form to the controller.

Do accept the post, we need to add a new Action to the controller, with the same name, but accepting a parameter of type RegisterModel:

public ActionResult Register(RegisterModel model)
{
    // do something with the model, such as inserting it into the database.
    // model.Firstname will contain the value of the firstname textbox
    // model.Surname will contain the value of the surnaem textbox

    return RedirectToAction("Success");
}

One last thing to do, to be safe, is to add the [HttpGet] and [HttpPost] attributes to your controller actions to control the methods they accept:

[HttpGet]
public ViewResult Register()

and

[HttpPost]
public ActionResult Register(RegisterModel model)

I suggest you read up on MVC at http://www.asp.net/mvc and read the NerdDinner tutorial chapter in Professional MVC (available for free online in PDF format).

like image 174
Michael Shimmins Avatar answered Sep 28 '22 19:09

Michael Shimmins