开发者

Responding to Xml/Json requests ala Rails

开发者 https://www.devze.com 2023-02-11 04:15 出处:网络
For example, from Rails Guides. def index @posts = Post.all respond_to do |format| format.html # i开发者_如何学Gondex.html.erb

For example, from Rails Guides.

def index
  @posts = Post.all

  respond_to do |format|
    format.html # i开发者_如何学Gondex.html.erb
    format.xml  { render :xml => @posts }
  end
end

If I invoke this controller and the request type is html, you are given a view. If the request type is xml, you are given XML. Nothing new here.

What's the best way of doing this in ASP.NET MVC? I know you can dig down into the request but I'm curious as to what others do. I'm not asking how to check the request to see what the request type is, I know how to do that, I'm looking for any standards or cool ways people handle this. There are probably some really nice ways of handling this and I'm looking for some ideas.

In fact, I'm pretty surprised that the framework hasn't copied this from Rails.


You may take a look at MVCContrib's simply RESTful routing.


Perhaps something like this?

public class MyController : Controller
{
    public ActionResult Index()
    {
        var posts = db.GetTable<Post>();
        ViewData["Posts"] = posts;

        return RespondTo(new ActionResultChoiceMap
        {
            { "html", () => View()      },
            { "json", () => Json(posts) },
        });
    }
}

with

class ActionResultChoiceMap : IEnumerable<ActionResultChoice>
{
     public void Add(string key, Func<ActionResult> handler);
     public ActionResult Get(string key);
}

and

ActionResult RespondTo(ActionResultChoiceMap map)
{
    var key = ... // get desired result type from request
    return map.Get(key);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消