BrunoLM
BrunoLM

Reputation: 100381

How to add logic to a User View Control in MVC 3?

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...

Upvotes: 0

Views: 4453

Answers (5)

Linora
Linora

Reputation: 10998

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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:

Upvotes: 7

heads5150
heads5150

Reputation: 7463

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

Upvotes: 0

stack72
stack72

Reputation: 8288

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?

Upvotes: 1

Related Questions