Home > Mobile >  ASP.NET button click event
ASP.NET button click event

Time:02-23

I am new to asp.net, and I was asked to build a restful API with the platform, I managed and got to build the API perfectly and it is working 100%, I now have to build a front-end for the API. it is just to manage email layout. the API is used to capture details, post into DB, and send emails. That portion is working.

My problem comes here, with the front-end, the whole MVC structure I cant seem to understand.

My goal: to have c# code executed when a button is clicked.

The first page I want to build is a login page. I already wrote all the c# models to create the user and save into db. I just want to figure out HOW to run my c# functions when a button is clicked.

It does not help to use asp:button because I cant generate click event for there is no c# code behind pages... the views I am using are MCV 5 view page (razor)

my HTML markup:

<div >

        <h1>Create an account</h1>

        <div >

            <div >


                <input placeholder="company name" />

            </div>

            <div >


                <input placeholder="username" />

            </div>

            <div >

                <input placeholder="password" type="password" />

            </div>

            <div >

                <input placeholder="confirm password" type="password" />

            </div>

            <div >

               <button onclick="" type="button">Register</button>


                


                <a href="">@Html.ActionLink("Back to Login", "Login", "Account")</a>

            </div>
           
        </div>


    </div>

the c# function I want to run when the button is clicked:

public void registerUser(User newUser)
        {
            dataAccess da = new dataAccess();

           if(!string.IsNullOrWhiteSpace(newUser.username) || !string.IsNullOrWhiteSpace(newUser.password) || !string.IsNullOrWhiteSpace(newUser.companyname))
            {
                try
                {

                    //all good, register user
                    da.insertUser(newUser);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

the data access class just contains a function that runs my SQL stored procedure to insert a user.

CodePudding user response:

There are different ways through which you can send your data to your Controller method on the server. I will show you how a very basic way on you can achieve your registration functionality using a strongly typed Model that will hold your registration details and then send it to the server for processing:

Create a Model under your Model directory called Register:

public class Register
{
    [Required]
    public string CompanyName { get; set; }

    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}

Then initialize this Model when you are rendering your initial view. Under your Controllers folder, create a new controller called Register and inside that define a method called Index. This method is responsible for setting up your Index view with the model bind to the fields:

using project.Models;

public class RegisterController : Controller
{
    public ActionResult Index()
    {
        Register register = new Register();
        return View(register);
    }
}

Now this controller method is responsible for routing the action to the Index view with the Register model. You can use HtmlHelpers to bind the value of the input to the model value like this. You should wrap your elements in a form that you will post to your Controller:

Index.cshtml:

@using project.Models
@model Register

<div >
    <h1>Create an account</h1>
    @Html.ValidationSummary(true, null, new { @class = "text-danger", style = "font-size:20px"})
    @using (Html.BeginForm("Register", "Register", FormMethod.Post, new { @class = "form", role = "form", enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        <div >
            <div >
                @Html.TextBoxFor(m => m.CompanyName , new { @id = "companynameID", @class = "form-control", @required = "required", @placeholder = "Enter Company Name", @autocomplete = "off" })           
            </div>
            <div >
                @Html.TextBoxFor(m => m.UserName , new { @id = "usernameID", @class = "form-control", @required = "required", @placeholder = "username", @autocomplete = "off" })               
                <input placeholder="username" />
            </div>
            <div >
                @Html.TextBoxFor(m => m.Password, new { @id = "passwordID", @class = "form-control", @required = "required", @placeholder = "Enter Password", @autocomplete = "off", @type = "password" })      
                <input placeholder="password" type="password" />
            </div>
            <div >
                <input placeholder="confirm password" type="password" id="confirmpasswordID"/>
            </div>      
            <div >
               <button type="submit" >Register</button>
            </div>      
        </div>
    }
    <br>
    <a href="">@Html.ActionLink("Back to Login", "Login", "Account")</a>    
</div>

The above View uses Bootstrap elements to display the form. We also use the @Html.AntiForgeryToken() which you can read more on here

Now once your view is setup, you can Post your data to the Controller like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Register register)
{
    dataAccess da = new dataAccess();
    try
    {
        var result= da.insertUser(register);
        if(!da)
        {
            ModelState.AddModelError("", "Could not register");
        }
        else
        {
            ModelState.AddModelError("", "Successfully registered");                
        }
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", "Exception in registering user");
        //Log the exception
    }           
    return View("Index", register);
}

There are other ways also in which you can send your form data to your Controller methods like using AJAX or JQuery to validate your elements first and then send them to Controller. The above implementation is a basic outline of how you can post your data through a Model.

  • Related