如何在mvc 4 razor中获取视图名称

时间:2015-12-02 06:42:28

标签: c# asp.net-mvc asp.net-mvc-4 razor

我想阅读活动的视图名称并将其填充到ViewName公共类

我创建了一个模型类,我用

获取textBox数据
public string ViewName { get; set; }
public string Name { get; set; }       
public string Email { get; set; }
public string Comment { get; set; }

在布局中我已经在表单标签中编写了一个代码,它在其余的公共字符串类中发送文本框值

<form method="post" action="/Home/SendMail" id="contactfrm" role="form">
                    <div class="col-sm-4">
                        <div class="form-group">
                            <label for="name">Name</label>
                            @Html.TextBox("Name", null, new { id = "name", @class = "form-control", placeholder = "Enter name", title = "Please enter your name (at least 2 characters)" })
                        </div>
                        <div class="form-group">
                            <label for="email">Email</label>
                            @Html.TextBox("Email", null, new { id = "email", @class = "form-control", placeholder = "Enter name", title = "Please enter a valid email address)" })
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="form-group">
                            <label for="comments">Comments</label>
                            @Html.TextArea("Comment", null, new { id = "comments", @class = "form-control", TextMode = "MultiLine", Columns = "3", Rows = "5", placeholder = "Enter your message…", title = "Please enter your message (at least 10 characters)" })
                        </div>
                        <button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Send Your Message</button>
                        <div class="result"></div>
                    </div>
                </form>

我想要做什么现在我想要读取活动视图名称也用于填充ViewName公共类,对于以相同视图再次回发它在布局中是活动的。你们有没有想过如何阅读viewName并将其填入Public Class?请告诉我在哪里可以添加表格标签。

提前谢谢

2 个答案:

答案 0 :(得分:1)

有两种方法可以在Razor View上获得View hame。

首先是View上的VirtualPath属性,您可以从路径获取视图名称:

@Path.GetFileNameWithoutExtension(Server.MapPath(VirtualPath))

第二个是ViewContext,但只有当您使用MVC对话并在控制器return View()中调用而没有明确传递视图名称时,它才会起作用。

@ViewContext.RouteData.Values["controller"].ToString()

答案 1 :(得分:0)

如果您使用RazorView 您可以通过以下代码获取视图路径:

(this.ViewContext.View as RazorView).ViewPath
相关问题