简体   繁体   English

ASP.net MVC 5从控制器加载HTML.Partial而不是在CSHTML页面上加载

[英]ASP.net MVC 5 loading HTML.Partial from controller instead of loading on cshtml page

new to MVC so here goes. MVC的新功能,因此在这里。

I am currently loading up HTML.Partial on my Index.cshtml page like so: 我目前正在Index.cshtml页面上加载HTML.Partial ,如下所示:

@Html.Partial("~/Views/Switchb/editPerson.cshtml")

However, I am in need of customizing that in the controller depending on the current users category number . 但是,我需要根据当前用户类别编号在控制器中进行自定义。

So as an example, if the user has a category of 3 then I would need to do this: 因此,例如,如果用户的类别为3,则需要这样做:

@Html.Partial("~/Views/Switchb/3.cshtml")

Is there any type of call in the "code behind" in the controller that I can use in order to do that? 我可以使用控制器中的“背后代码”中的任何类型的调用来执行此操作吗? Or would I just need to place the code within the cshtml page and pass its category number via the controller over to the cshtml page? 还是只需要将代码放在cshtml页面中,并通过控制器将其类别号传递到cshtml页面?

You can render a partial view from a controller action. 您可以从控制器动作中渲染局部视图。 You can pass the view name as string. 您可以将视图名称作为字符串传递。

public ActionResult Switchb(string categoryNumber) {
    var viewModel = new MyViewModel { CategoryNubmer = categoryNumber };
    // additional processing, backend calls, formatting ....
    return PartialView(categoryNumber, viewModel);
}

To call this action from View: 要从View调用此操作:

@{
    var routeValues = new RouteValueDictionary(new {
        categoryNumber= "3",
    });
    Html.RenderAction("Switchb", "MyController", routeValues);
}

Determine the category in the controller (via url parameter, from a database, or whatever) and then set that value as a property on your view's Model. 确定控制器中的类别(通过url参数,数据库中的内容或其他内容),然后将该值设置为视图模型的属性。 Then in your line of code you can do this 然后在您的代码行中可以执行此操作

@Html.Partial("~/Views/Switchb/" + Model.Category + ".cshtml");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM