开发者

Calling a method in the controller

I'm a newbie about ASP.NET MVC 3, but I have a simple question. Is it possible to call a Controller method from an CSHTML (Razor) page?

Example:

xxxControl.cs:

public String Bla(TestModel pModel)
{
    return ...
}

index.cshtml:

@Bla(Model) <-- Error

Thanks.

Update:

Thanks @Nathan. This isn't a good idea to do this on this way. The goal is: I need some formatting strin开发者_高级运维g for a field of the Model. But where I put the code that return a formatting String in the case?


It is considered bad practice for a view to call methods located on a controller. Usually it is a controller action which populates a model and passes this model to the view. If you needed some formatting on this model you could write an HTML helper.

public static class HtmlExtensions
{
    public static IHtmlString Bla(this HtmlHelper<TestModel> htmlHelper)
    {
        TestModel model = htmlHelper.ViewData.Model;
        var value = string.Format("bla bla {0}", model.SomeProperty);
        return MvcHtmlString.Create(value);
    }
}

and in your view:

@Html.Bla()


That would make unit-testing your mvc site very difficult.

Are you needing a partial view maybe? (what are you actually trying to do?)


Yes it's possible.

@using Nop.Web.Controllers;
 @
 var _CatalogController = EngineContext.Current.Resolve<CatalogController>();
 var _model = new ProductModel();
 _model = _CatalogController.PrepareProductOverviewModel(p, true, true);
}

Set the method to public if it is private.

Even the services you can call in the same manner.

var _productService = EngineContext.Current.Resolve<IProductService>();
if (Model.SubCategories.Count > 0)
{
foreach (var SubCategories in Model.SubCategories)
{
 int subcategoryid = SubCategories.Id;<br>
 IPagedList<Product> _products = _productService.SearchProducts(subcategoryid,0, null, null, null, 0, string.Empty, false, 0,null,ProductSortingEnum.Position, 0, 4);
}
i++
}


Simply do it like this:

xxxControl.cs action method:

public ActionResult YourView(TestModel pModel) {

    //pMomdel code here

    ViewBag.BlaResult = Bla(pModel);
    return View(pModel);
}

index.cshtml:

@ViewBag.BlaResult
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜