How to set the static text into JsonResult?

懵懂的女人 提交于 2019-12-08 00:46:16

问题


I found the following code example (from Telerik ) that I'm trying to understand. What I need to do is somehow to set static text into JsonResult (e.g.Text ="Abc" and Value="123")

    public ActionResult _AjaxLoading(string text)
    {
        Thread.Sleep(1000);
        using ( var nw = new NorthwindDataContext() )
        {
            var products = nw.Products.AsQueryable();
            if ( text.HasValue() )
            {
                products = products.Where((p) => p.ProductName.StartsWith(text));
            }
            return new JsonResult { Data = new SelectList(products.ToList(), "ProductID", "ProductName") };
        }
    }

回答1:


Is this what you are looking for

return new JsonResult { Text = "Abc", Value="123" };

If you want to add a new element to the drop down at start then

var editedProducts = new SelectList(products.ToList(), "ProductID","ProductName" ).ToList();
editedProducts.insert(0, new SelectListItem() { Value = "123", Text = "Abc" });

return new JsonResult { Data = editedProducts };



回答2:


public ActionResult _AjaxLoading(string text
{
  var data = new { Text= "123", Value= "Abc"};
  return Json(data, JsonRequestBehavior.AllowGet);
}

If it is an HTTPGet method, You should specify JsonRequestBehavior.AllowGet as second parameter to return JSon data from a GET method




回答3:


It looks like you are in need of this:

return new JsonResult { Data = new { Text="Abc", Value="123", Produtcs= new SelectList(products.ToList(), "ProductID", "ProductName") }};


来源:https://stackoverflow.com/questions/10500823/how-to-set-the-static-text-into-jsonresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!