Question

User View Control doesn't have a code-behind. So, where/how should I make the events of elements?

I want to understand a logic of a control in MVC...

Was it helpful?

Solution

There are no user controls in MVC so you shouldn't bother about logic of a control. There are no PostBacks in MVC. There is no ViewState in MVC. There are no events in MVC.

There are models:

public class MyViewModel
{
    public string Name { get; set; }
}

Controllers manipulating the model:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Name = "John"
        });
    }
}

and Views rendering the data contained in the model:

@model AppName.Models.MyViewModel
<div>@Model.Name</div>

When views need to call something into the controller they no longer use any PostBacks or events: they use standard HTML artifacts such as anchor links for sending GET requests and forms for sending POST requests.

Example:

@Html.ActionLink("click me", "Foo", new { param = "123" })

would generate an anchor link to the Foo controller action passing param=123 as query string parameter:

<a href="/home/foo?param=123">click me</a>

and the following:

@using (Html.BeginForm("Foo", "Home"))
{
    @Html.TextBoxFor(x => x.Name)
    <input type="submit" value="OK">
}

would generate an HTML form allowing you to POST to the Foo controller action some information:

<form action="/Home/Foo" method="post">
    <input type="text" id="Name" name="Name" value="" />
    <input type="submit" value="OK" />
</form>

Useful resources with many tutorials and videos for learning ASP.NET MVC:

OTHER TIPS

Personally id do the logic in the controller or have the controller call a business logic class that does the work for you. the controller will then return the View. Pass the model into your view from the controller and then pass the model from the view into the partial view (MVC equivalent of a user control)

this will mean there is no logic in the View/ Partial View and will mean that you can render the model in a very clean way

does this make sense?

You do seem to be too attached to the WebForms page lifecycle.

The programming methodology on the surface for MVC is fundamentally different to WebForms. It's more akin to Ruby On Rails.

Some resources to help you learn MVC are:

Official MVC Web site

Scott Hanselman's NerdDinner project

I'll also recommend Scott Hanselman's NerdDinner project.. Its a great project to learn the ASP.NET MVC framework.

Also read and re-read Darin Dimitrov's answer.. it contains the basics of how data is handled in MVC

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top