2011-10-07 77 views
60

有沒有其他方法可以從控制器返回原始html?與僅使用viewbag相反。如下圖所示:asp.net mvc3返回原始html來查看

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     ViewBag.HtmlOutput = "<HTML></HTML>"; 
     return View(); 
    } 
} 

@{ 
    ViewBag.Title = "Index"; 
} 

@Html.Raw(ViewBag.HtmlOutput) 
+0

我承認有很多原因直接注入html,但我很好奇你爲什麼在這種情況下? – Rikon

+3

我有一些遺產代碼,它會從dll生成標記。 – River

回答

112

這樣做沒有太大意義,因爲View應該生成html,而不是控制器。但不管怎麼說,你可以使用Controller.Content method,它給你指定的HTML結果,也是內容類型和編碼

public ActionResult Index() 
{ 
    return Content("<html></html>"); 
} 

或者你可以使用內置在asp.net-MVC框架的伎倆能力 - 使動作返回字符串直。它會將字符串內容傳送到用戶的瀏覽器中。

public string Index() 
{ 
    return "<html></html>"; 
} 

事實上,比其他ActionResult任何作用的結果,框架,嘗試將其序列化到字符串寫入響應。

+0

我同意視圖生成html。我的內容思想是從傳統的dll生成的。如果控制器不適合調用,那麼可能是模型? – River

+0

這對使用返回類型的字符串很有趣。那一直有效嗎? –

+0

是的。任何不是ActionResult的都會轉換爲字符串並返回響應 – archil

1

,除非你想要把它作爲示範串

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     string model = "<HTML></HTML>"; 
     return View(model); 
    } 
} 

@model string 
@{ 
    ViewBag.Title = "Index"; 
} 

@Html.Raw(Model) 
7

只需創建型MvcHtmlString您的視圖模型一個屬性,看起來不錯。你也不需要Html.Raw它。

+0

謝謝。沒有使用你所說的。你說的幫助我找出使用[DataType.Html] – Dexter

3

給一個嘗試返回引導警報消息,這個工作對我來說

return Content("<div class='alert alert-success'><a class='close' data-dismiss='alert'> 
&times;</a><strong style='width:12px'>Thanks!</strong> updated successfully</div>"); 

注:不要忘記添加引導cssjs在您的視圖頁面

希望幫助有人。

+0

謝謝,它真的幫了我:) – rentire

-1

在控制器,你可以使用MvcHtmlString

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     string rawHtml = "<HTML></HTML>"; 
     ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml); 
     return View(); 
    } 
} 

在你看來,你可以簡單地使用,你在你的控制器一樣設置動態屬性下面

<div> 
     @ViewBag.EncodedHtml 
</div> 
-1

控制器

public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
     ViewBag.show = false; 
     return View(); 
     } 
     } 

Views

@{ 
     ViewBag.Title = "Index"; 
     } 

    @if (ViewBag.show == false){ 
     <div > 
      @*your code*@ 
     </div> 
     }