Development Tip

MVC에서 문자열 결과를 어떻게 반환합니까?

yourdevel 2020. 10. 2. 23:26
반응형

MVC에서 문자열 결과를 어떻게 반환합니까?


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

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


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

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

ContentResult기본적 text/plain으로는 contentType 으로 반환 됩니다 . 이것은 오버로드 가능하므로 다음을 수행 할 수도 있습니다.

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); 
}

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

먼저

문자열 만 반환 할 수 있지만 html 파일에는 포함되지 않습니다. 브라우저에 jus 문자열이 표시됩니다.


둘째

결과보기의 객체로 문자열을 반환 할 수 있습니다.

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

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 에서 실행합니다 .

참고 URL : https://stackoverflow.com/questions/553936/in-mvc-how-do-i-return-a-string-result

반응형