如何将参数从控制器(Content.ReadAsAsync)传递到mvc4中的api控制器

时间:2014-02-12 08:42:45

标签: asp.net-mvc-4 asp.net-web-api parameter-passing

这是我的控制器

public ActionResult Index(string Searchby, string SearchValue)
    {
        var client = new HttpClient();
        var productDetailUrl = Url.RouteUrl(
            "DefaultApi",
            new { httproute = "", controller = "Assets" },
            Request.Url.Scheme
        );
        var model = client
                    .GetAsync(productDetailUrl)
                    .Result
                    .Content.ReadAsAsync<AssetDetails[]>().Result;

        return View(model);}

searchby和searchvalue params正在形成

<script type="text/javascript">

$(function () {
    $('#txtSearch').blur(function () {
        var Searchby = $('select[name="Searchby"]').val();
        var SearchValue = $("txtSearch").val();
        $.ajax({
            type: "POST",
            url: '/Asset/Index',
            data: { Searchby: searchby, SearchValue: SearchValue },
        })
    });
});

我应该如何从ReadAsAsync传递Searchby,SearchValue

1 个答案:

答案 0 :(得分:0)

将你的uri打造成一根绳子。从您的代码中不清楚您想要请求的是什么,所以我建议它看起来如何。我还将代码转换为使用异步模式以避免死锁。

public async Task<ActionResult> Index(string Searchby, string SearchValue)
{
    var productDetailUrl = string.Format("http://<hostname>/you/uri/here?searchBy={0}&searchValue={1}", SearchBy, SearchValue);

    var client = new HttpClient();
    var response = await client.GetAsync(productDetailUrl);
    var model = await response.Content.ReadAsAsync<AssetDetails[]>();

    return View(model);
}