[asp.net-mvc] MVC에서 문자열 결과를 어떻게 반환합니까?

내 AJAX 호출에서 문자열 값을 호출 페이지로 다시 반환하고 싶습니다.

ActionResult문자열을 사용 하거나 반환 해야합니까 ?



답변

를 사용하여 ContentResult일반 문자열을 반환 할 수 있습니다 .

public ActionResult Temp() {
    return Content("Hi there!");
}

ContentResult기본적으로 a text/plaincontentType 으로 반환합니다 . 오버로드 가능하므로 다음을 수행 할 수도 있습니다.

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");


답변

메소드가 리턴 할 유일한 것임을 알고 있다면 문자열을 리턴 할 수도 있습니다. 예를 들면 다음과 같습니다.

public string MyActionName() {
  return "Hi there!";
}


답변

public ActionResult GetAjaxValue()
{
   return Content("string value");
}


답변

public JsonResult GetAjaxValue()
{
  return Json("string value", JsonRequetBehaviour.Allowget);
}


답변

2020 년 ContentResult부터는 위에서 제안한 대로 올바른 방법을 사용하지만 사용법은 다음과 같습니다.

return new System.Web.Mvc.ContentResult
{
    Content = "Hi there! ☺",
    ContentType = "text/plain; charset=utf-8"
}


답변

컨트롤러에서보기로 문자열을 반환하는 두 가지 방법이 있습니다

먼저

문자열 만 반환 할 수는 있지만 HTML 파일에는 포함되지 않습니다. 브라우저에 jus 문자열이 나타납니다.

둘째

View Result의 객체로 문자열을 반환 할 수 있습니다

이 작업을 수행하는 코드 샘플은 다음과 같습니다.

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을 가로 리디렉션됩니다 결과 보기를하고 보내드립니다
보기로 코드를

<!--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>

http : // localhost : 60227 / Home / AutoProperty 에서 실행합니다 .


답변