[ajax] JSON 또는 부분 HTML을 반환하는 ASP.NET MVC 컨트롤러 작업

매개 변수에 따라 JSON 또는 부분 html을 반환하는 컨트롤러 작업을 만들려고합니다. 결과를 MVC 페이지에 비동기 적으로 반환하는 가장 좋은 방법은 무엇입니까?



답변

액션 메소드에서 Json (object)을 반환하여 JSON을 페이지로 반환하십시오.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

그런 다음 Ajax를 사용하여 액션 메소드를 호출하십시오. ViewPage에서 다음과 같은 도우미 메소드 중 하나를 사용할 수 있습니다.

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

SomeMethod는 반환 된 Json 객체를 평가하는 자바 스크립트 메소드입니다.

일반 문자열을 반환하려면 ContentResult를 사용하면됩니다.

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

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

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


답변

요청의 AcceptTypes를 고려해야한다고 생각합니다. 현재 프로젝트에서 다음과 같이 올바른 내용 유형을 반환하기 위해 사용하고 있습니다.

컨트롤러에 대한 조치는 요청 오브젝트에서와 같이 테스트 할 수 있습니다.

if (Request.AcceptTypes.Contains("text/html")) {
   return View();
}
else if (Request.AcceptTypes.Contains("application/json"))
{
   return Json( new { id=1, value="new" } );
}
else if (Request.AcceptTypes.Contains("application/xml") ||
         Request.AcceptTypes.Contains("text/xml"))
{
   //
}

그런 다음 부분적인 xhtml 응답 사례를 제공하기 위해보기의 aspx를 구현할 수 있습니다.

그런 다음 jQuery에서 유형 매개 변수를 json으로 전달하여 가져올 수 있습니다.

$.get(url, null, function(data, textStatus) {
        console.log('got %o with status %s', data, textStatus);
        }, "json"); // or xml, html, script, json, jsonp or text

이것이 제임스에게 도움이되기를 바랍니다.


답변

JSON 데이터를 처리하는 또 다른 좋은 방법은 JQuery getJSON 함수를 사용하는 것입니다. 당신은 전화 할 수 있습니다

public ActionResult SomeActionMethod(int id)
{
    return Json(new {foo="bar", baz="Blech"});
}

간단하게 jquery getJSON 메소드의 메소드 …

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);


답변

JQuery로 MVC ajax GET 호출을 구현하는 몇 가지 문제가있어 두통을 일으켜 솔루션을 공유했습니다.

  1. Ajax 호출에 데이터 유형 “json”을 포함시켜야합니다. 이것은 반환 된 JSON 객체를 자동으로 구문 분석합니다 (서버가 유효한 json을 반환하면).
  2. 포함 JsonRequestBehavior.AllowGet; 이 MVC가 없으면 HTTP 500 오류를 반환했습니다 (dataType: json 클라이언트에 지정된 .
  3. cache: false$ .ajax 호출에 추가하십시오 . 그렇지 않으면 결과적으로 HTTP 200 응답 대신 HTTP 304 응답이 표시되고 서버는 요청을 처리하지 않습니다.
  4. 마지막으로 json은 대소 문자를 구분하므로 요소의 케이스는 서버 측과 클라이언트 측에서 일치해야합니다.

샘플 JQuery :

$.ajax({
  type: 'get',
  dataType: 'json',
  cache: false,
  url: '/MyController/MyMethod',
  data: { keyid: 1, newval: 10 },
  success: function (response, textStatus, jqXHR) {
    alert(parseInt(response.oldval) + ' changed to ' + newval);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert('Error - ' + errorThrown);
  }
});

샘플 MVC 코드 :

[HttpGet]
public ActionResult MyMethod(int keyid, int newval)
{
  var oldval = 0;

  using (var db = new MyContext())
  {
    var dbRecord = db.MyTable.Where(t => t.keyid == keyid).FirstOrDefault();

    if (dbRecord != null)
    {
      oldval = dbRecord.TheValue;
      dbRecord.TheValue = newval;
      db.SaveChanges();
    }
  }

    return Json(new { success = true, oldval = oldval},
                JsonRequestBehavior.AllowGet);
}


답변

질문의 나머지 절반에 답하려면 다음으로 전화하십시오.

return PartialView("viewname");

부분 HTML을 반환하려는 경우 URL 부분 / 매개 변수를 기반으로 요청이 JSON 또는 HTML을 원하는지 여부를 결정하는 방법을 찾아야합니다.


답변

인코딩 프레임 워크가있는 대체 솔루션

액션 리턴 JSON

제어 장치

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
    }

면도기 페이지

@using (var template = Html.Incoding().ScriptTemplate<SomeVm>("tmplId"))
{
    using (var each = template.ForEach())
    {
        <span> Id: @each.For(r=>r.Id) Name: @each.For(r=>r.Name)</span>
    }
}

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core()
                              .Insert
                              .WithTemplate(Selector.Jquery.Id("tmplId"))
                              .Html())
  .AsHtmlAttributes()
  .ToDiv())

액션 리턴 HTML

제어 장치

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncView();
    }

면도기 페이지

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core().Insert.Html())
  .AsHtmlAttributes()
  .ToDiv())


답변

이 기사를 매우 훌륭하게 다루는이 유용한 기사를 살펴보십시오.

사람들 이이 문제에 대한 좋은 해결책을 찾는 데 도움이 될 수 있다고 생각했습니다.

http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx