How to set the static text into JsonResult?

2019-05-25 17:44发布

问题:

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") }};