Özgür Kara
Özgür Kara

Reputation: 1333

Get data from a controller in another controller

I am trying to build a generic export operation in mvc. so i wrote a controller for this.

[AcceptVerbs(HttpVerbs.Post)]
public string Excel(FormCollection collection)
{
    string dataUrl = collection["dataUrl"];
    string filter = collection["filter"];
    //Get data from dataUrl
    ...
}

My problem is I want to get data to be transferred from another controller by passing same parameter to its method via POST.

this is the sample method for data

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult List(FormCollection collection)
{
    ...
    return Json(data);
}

Thanks in advance.

Upvotes: 0

Views: 1327

Answers (2)

BentOnCoding
BentOnCoding

Reputation: 28168

Assuming you absolutely have to call controller to controller you can use an HttpWebRequest like so:

public void CallController()
    {
        var request = (HttpWebRequest)WebRequest.Create("http://yoursite.com/Excel");
        request.Method = "POST";

        using (var dataStream = request.GetRequestStream())
        {
            //write your data to the data stream
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    //work with the controller response
                }
            }
        }
    }

This is very inefficient if you can refactor the code into a class external to both controllers.

Upvotes: 0

Quinton Bernhardt
Quinton Bernhardt

Reputation: 4803

Why not refactor the export code into a utility class and then use it from both controllers?

Upvotes: 1

Related Questions