开发者

ASP.NET Button Click event does not appear to fire

I'm relatively new to ASP.NET. I have a ASP.NET MVC 2 Web Application project (created in开发者_运维问答 Visual Studio 2010). I added a method to HomeController called Search

public ActionResult Search()
{
    return View();
}

and created a corresponding view (web page) called Search.aspx onto which I dropped a button. I double-clicked the button to add a handler for the button click event which sets the text of a TextBox, then built the application.

<script runat="server">


protected void MyButton1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine("Undo button clicked");
    m_search_text_box.Text = "MyButton1_Click";
}

...

When I click the button in my browser (I tested in Chrome and Internet Explorer), nothing happens. The text box is not updated. Nothing is written to the Output window either. So, it doesn't look like the event is firing. Can anybody offer any suggestions? I'm using Visual Studio 2010 on Windows 7.

Thanks


You are mixing WebForms event handling into an MVC app. MVC does not work like WebForms. Check out the tutorials on MVC2 to help get you started down the right path.

Here's a sample app with step by step tutorials to help get to the basics of MVC down.


ASP.NET MVC doesn't use code behind handlers like that. You use controller actions to respond to requests, and decide how to visually handle them (ie: you can render a view, or return a JSON object, or redirect to another Action etc).

In your instance, if you want to put some text in a textbox after the user has clicked the button, you'd want to put a Submit button in a form, and create a controller action to respond to it:

[HttpPost]
public ActionResult Search()
{
    var model = new SearchModel();
    model.StatusText = "MyButton1_Click";

    return View(model);
}

In your view, you want to use this model, and put its StatusText property value into a textbox:

<%= Html.TextBoxFor(x => x.StatusText) %>

Have a look at the ASP.NET MVC website which has a lot of great getting started tutorials, and the Nerd Dinner tutorial (a free chapter in the book).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜