简体   繁体   English

ASP.NET 按钮点击事件

[英]ASP.NET button click event

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.我是 asp.net 的新手,我被要求用该平台构建一个宁静的 API,我设法完美地构建了 API,它工作 100%,我现在必须为 API 构建一个前端。它是只是为了管理 email 布局。 the API is used to capture details, post into DB, and send emails. API 用于捕获详细信息、发布到数据库和发送电子邮件。 That portion is working.那部分正在工作。

My problem comes here, with the front-end, the whole MVC structure I cant seem to understand.我的问题来了,前端,整个 MVC 结构我似乎无法理解。

My goal: to have c# code executed when a button is clicked.我的目标:单击按钮时执行 c# 代码。

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.我已经编写了所有 c# 模型来创建用户并保存到数据库中。 I just want to figure out HOW to run my c# functions when a button is clicked.我只想弄清楚如何在单击按钮时运行我的 c# 函数。

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)使用 asp:button 没有帮助,因为我无法生成点击事件,因为页面后面没有 c# 代码...我使用的视图是 MCV 5 视图页面(剃刀)

my HTML markup:我的 HTML 标记:

<div class="lg-conatiner">

        <h1>Create an account</h1>

        <div class="loginBox registerBox">

            <div class="loginItem">


                <input placeholder="company name" />

            </div>

            <div class="loginItem">


                <input placeholder="username" />

            </div>

            <div class="loginItem">

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

            </div>

            <div class="loginItem">

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

            </div>

            <div class="loginItem loginItem3">

               <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: c# function 我想在单击按钮时运行:

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.数据访问 class 只包含一个 function,它运行我的 SQL 存储过程来插入用户。

There are different ways through which you can send your data to your Controller method on the server.您可以通过多种方式将数据发送到服务器上的Controller方法。 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:我将向您展示如何使用强类型Model实现注册功能的一种非常基本的方法,它将保存您的注册详细信息,然后将其发送到服务器进行处理:

Create a Model under your Model directory called Register:在你的 Model 目录下创建一个Model名为 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.然后在渲染初始视图时初始化此Model Under your Controllers folder, create a new controller called Register and inside that define a method called Index .在您的 Controllers 文件夹下,创建一个名为Register的新 controller 并在其中定义一个名为Index的方法。 This method is responsible for setting up your Index view with the model bind to the fields:此方法负责使用绑定到字段的 model 设置您的索引视图:

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.现在这个 controller 方法负责将操作路由到寄存器 model 的索引视图。您可以像这样使用HtmlHelpers将输入的值绑定到 model 值。 You should wrap your elements in a form that you will post to your Controller :您应该将您的元素包装在您将发布到您的Controllerform中:

Index.cshtml : Index.cshtml

@using project.Models
@model Register

<div class="lg-conatiner">
    <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 class="loginBox registerBox">
            <div class="loginItem">
                @Html.TextBoxFor(m => m.CompanyName , new { @id = "companynameID", @class = "form-control", @required = "required", @placeholder = "Enter Company Name", @autocomplete = "off" })           
            </div>
            <div class="loginItem">
                @Html.TextBoxFor(m => m.UserName , new { @id = "usernameID", @class = "form-control", @required = "required", @placeholder = "username", @autocomplete = "off" })               
                <input placeholder="username" />
            </div>
            <div class="loginItem">
                @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 class="loginItem">
                <input placeholder="confirm password" type="password" id="confirmpasswordID"/>
            </div>      
            <div class="loginItem loginItem3">
               <button type="submit" class="btn btn-block btn-primary">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.上面的 View 使用Bootstrap元素来显示表单。 We also use the @Html.AntiForgeryToken() which you can read more on here我们还使用@Html.AntiForgeryToken()你可以在这里阅读更多

Now once your view is setup, you can Post your data to the Controller like this:现在,一旦您的视图设置完毕,您就可以像这样将数据PostController

[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 .还有其他方法可以将表单数据发送到Controller方法,例如使用AJAXJQuery首先验证您的元素,然后将它们发送到Controller The above implementation is a basic outline of how you can post your data through a Model .上面的实现是关于如何通过Model发布数据的基本概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM