如何在Razor View中声明Html.ActionLink类型的变量

时间:2018-03-20 16:00:19

标签: html asp.net-mvc razor

我可以声明什么类型的Html.ActionLink类型的变量,这样当我渲染此变量时,它会正常渲染。这就是我想要做的。

@{
    var action = @Html.DisplayFor(m => invoice.TransactionAction.Action);
    var link = "";
    var actionLink = "";
}
@{
    if (!String.IsNullOrEmpty(action.ToString()))
    {
        switch (action.ToString())
        {
            case "Receive Payment":
                link = "Receive Payment";
                actionLink = Html.ActionLink(@action.ToString(), @link, "Sales", new { id = invoice.Id }, null).ToString();
                break;
            case "Print":
                link = "Print";
                actionLink = Html.ActionLink(@action.ToString(), @link, "Sales", new { id = invoice.Id }, null).ToString();
                break;
        }
    }
} 

每当我渲染@actionLink时,它会显示类似<a href="/Sales/Receive%20Payment/7">Receive Payment</a>的内容,我理解为与助手方法ActionLink等效的ToString()。

因为我需要显示链接或null,我想知道声明actionLink的类型。

P.S:我已经尝试了var actionLink = Html.ActionLink("Sample", "Sample", "Sales");但当然是空渲染的样本,而不是不打印任何东西。

1 个答案:

答案 0 :(得分:0)

ActionLink实际上返回MvcHtmlString并且razor引擎知道它需要将其呈现为html。

您应该将结果存储在该类型的变量中,然后您可以正常渲染它而不将其转换为src_Makefiles=$(wildcard *_src/Makefile) # Makefiles in source src_dirs=$(src_Makefiles:/Makefile=) # source directories build_dirs=$(src_dirs:_src=_build) # build directories built_files=$(build_dirs:=/.built) # build done files #default target, which builds everything: all: $(built_files) #for debugging only -- lets you know if you've made a mistake: $(info built_files=$(built_files)) # the following creates a _build directory for every _src directory. $(build_dirs) : %_build : %_src @echo updating $@ @rm -rf $@ # remove any artifacts from previous builds... @mkdir -p $@ # make the directory @cp -r $@ $^ # copy the entire contents of _src to build. # The following is the rule to build each directory. # Each built file depends on the _src directory (which # has a timestamp of the latest modified file -- so it # will rebuild only if the student has modified something # since the last build) $(built_files): %_build/.built : %_build @echo building $(dir $@) @echo "run make -C $(dir $@)" touch $@ clean: rm -rf *_build ,如:

String

然后你可以在视图的任何地方使用它,如:

MvcHtmlString actionLink = Html.ActionLink(@action.ToString(), 
                                           @link, 
                                           "Sales", 
                                           new { id = invoice.Id }, 
                                           null);

,这将呈现为html超链接。

或者,如果我们坚持使用您使用<div> @actionLink </div> 的方法,那么您可以Html.Raw将字符串呈现为html:

String

希望它有所帮助!