在Razor中,如何设置当前的模型范围?

时间:2022-04-19 20:15:08

I am not even sure how I would ask this question. Basically, you know how in Razor you have stuff like this:

我甚至不确定如何问这个问题。基本上,你知道在Razor中你有这样的东西:

@model MyProj.childObj
// Current scope is childObj
@Html.LabelFor(m => m.MyVal)
@Html.LabelFor(m => m.MyVal2)
@Html.LabelFor(m => m.MyVal3)
...

This all work fine and dandy, but what if I concat childObj into another obj? So for example:

这一切都很好,花花公子,但如果我将childObj连接到另一个obj怎么办?例如:

@model MyProj.parentObj

So now, I can do this:

所以现在,我可以这样做:

// Current scope is parentObj
@Html.LabelFor(m => m.childObj.MyVal)
@Html.LabelFor(m => m.childObj.MyVal2)
@Html.LabelFor(m => m.childObj.MyVal3)
...

which is fine, but since I have a lot of variable, I would like to do this instead:

这很好,但由于我有很多变量,我想这样做:

// Current scope is parentObj
@using (Model.childObj) {
    // Current scope is now childObj
    @Html.LabelFor(m => m.MyVal)
    @Html.LabelFor(m => m.MyVal2)
    @Html.LabelFor(m => m.MyVal3)
    ...
}

Is this possible?

这可能吗?

1 个解决方案

#1


1  

Yes. You can define variables within Razor and use them.

是。您可以在Razor中定义变量并使用它们。

@{
    var child = Model.childObj;
    @Html.LabelFor(m => child.MyVal)
    @Html.LabelFor(m => child.MyVal2)
    @Html.LabelFor(m => child.MyVal3)
}

#1


1  

Yes. You can define variables within Razor and use them.

是。您可以在Razor中定义变量并使用它们。

@{
    var child = Model.childObj;
    @Html.LabelFor(m => child.MyVal)
    @Html.LabelFor(m => child.MyVal2)
    @Html.LabelFor(m => child.MyVal3)
}