开发者

Bind property on ViewUserControl to localvariable in .NET MVC2

I want to do something like this where item is a local variable in the .aspx page:

<p:ProgressBar  runat="server" Progress="<%#item.Completed/item.Total%>" Width="100" />

the binding expression isn't detecting the local page level variables. Is there a w开发者_如何学JAVAay I can accomplish this wihtout using RenderPartial?


You shouldn't use any server side controls (runat="server") in an ASP.NET MVC application because that they rely on ViewState and PostBack which are notions that no longer exist in ASP.NET MVC. The only exception makes <asp:Content> panels used by the webforms view engine to implement master pages. Also there is no notion of binding.

In ASP.NET MVC you have a model, a controller and a view. The controller populates some model and passes it to the view to be shown. The view itself could use HTML helpers to generate simple markup or include other partial views for more complex scenarios.

So you start with defining a model:

public class MyViewModel
{
    public double Progress { get; set; }
}

then you have a controller which will manipulate this view model:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var completed = 5; // get this from somewhere
        var total = 10; // get this from somewhere
        var model = new MyViewModel
        {
            Progress = (1.0 * completed / total)
        }
        return View(model);
    }
}

and finally you would have a strongly typed view to this model where you would show the markup:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>" 
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Progress</h2>
    <div><%= Html.DisplayFor(x = x.Progress)</div>
</asp:Content>


The answer to this is that there really is not a good way to do this. You can pass in the model using the ViewDataKey properties, but you're stuck using keys that exist in the current ViewDictionary so you're going to add some cruft to the parent view by going this route.

If you want to set view-only properties, it may be possible using a custom HTML helper but probably just better off trying to find a work around as Darin alludes to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜