Method call in the controller

I am new to ASP.NET MVC 3, but I have a simple question. Can I call the controller method from the CSHTML (Razor) page?

Example:

xxxControl.cs:

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

index.cshtml:

@Bla(Model) <-- Error

Thank.

Update:

Thanks @Nathan. It is not a good idea to do this along the way. Purpose: I need a format string for the Model field. But where do I put code that returns String formatting in case?

+3
source share
4 answers

It is considered bad practice to call methods located on the controller. This is usually a controller action that populates the model and passes that 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 opinion:

@Html.Bla()
+18

mvc .

, ? ( ?)

+2

, .

@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 services that you can call in the same way.

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++
}
0
source

Just do the following:

xxxControl.cs action method:

public ActionResult YourView(TestModel pModel) {

    //pMomdel code here

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

index.cshtml:

@ViewBag.BlaResult
0
source

All Articles