回答:
を使用しContentResultてプレーンな文字列を返すことができます。
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResultデフォルトでは、a text/plainをcontentTypeとして返します。これはオーバーロード可能であるため、次のこともできます。
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
ContentResultはif (!String.IsNullOrEmpty(ContentType))設定前に正確ですHttpContext.Response.ContentType。私はtext/htmlあなたの最初の例を見ています、それが今のデフォルトであるか、それはによる知識に基づいた推測ですHttpContext。
MediaTypeNames.Text.Plainまたはのような.NETフレームワーク定数を使用できますMediaTypeNames.Text.Xml。ただし、最もよく使用されるMIMEタイプの一部しか含まれていません。(docs.microsoft.com/en-us/dotnet/api/...)
メソッドが返す唯一のものであることがわかっている場合は、単に文字列を返すこともできます。例えば:
public string MyActionName() {
return "Hi there!";
}
returnどちらか送信するために使用されている文stringまたはJSONあるいはViewそれから、我々が使用しなければならない条件に基づいてContent文字列を返すようにします。
2020年時点でContentResultも、上記で提案されているように使用することは依然として適切なアプローチですが、使用方法は次のとおりです。
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ☺",
ContentType = "text/plain; charset=utf-8"
}
コントローラからビューに文字列を返す方法は2つあります
最初
あなたは文字列のみを返すことができますが、htmlファイルには含まれませんそれはブラウザに表示される文字列です
二番目
ビュー結果のオブジェクトとして文字列を返すことができます
これはこれを行うためのコードサンプルです
public class HomeController : Controller
{
// GET: Home
// this will mreturn just string not html
public string index()
{
return "URL to show";
}
public ViewResult AutoProperty()
{ string s = "this is a string ";
// name of view , object you will pass
return View("Result", (object)s);
}
}
実行するために、ビューファイルにAutoPropertyをそれがためにリダイレクトされます結果表示をしてお送りしますsの
ビューにコードを
<!--this to make this file accept string as model-->
@model string
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Result</title>
</head>
<body>
<!--this is for represent the string -->
@Model
</body>
</html>