0

C# データソースで Kendo UI Autocomplete ツールを使用しようとしています。PHPでは非常に簡単に思えます:

    <?php
        include("connection.php");

    $arr = array();

    $stmt = $db->prepare("SELECT StateID, StateName FROM USStates WHERE StateName LIKE ?");

    // get the StartsWith value and append a % wildcard on the end
    if ($stmt->execute(array($_GET["StartsWith"]. "%"))) {
        while ($row = $stmt->fetch()) {
            $arr[] = $row;    
        }
    }

    // add the header line to specify that the content type is JSON
    header("Content-type: application/json");

    echo "{\"data\":" .json_encode($arr). "}";
?>

しかし、私は CSHtml ファイルまたは同等のものを使用したいのですが、これを達成する方法について何か考えがありますか?

模型などに付属するコントローラーを作りたくない… 1ページだけで作れたら良いのですが。

4

1 に答える 1

2

MVCを使用している場合そのようなコントローラーを作成します。

public class DataController : Controller
{
    public JsonResult GetStates()
    {
        var data = GetData();
        return Json(new
        {
            data = data.Select(r => new
            {
                StateId = r.ID,
                StateName = r.Name
            })
        });
    }
 }

次に、データソースのURLを/ data/GetStatesに設定するだけです。

Webフォームを使用している場合は、ジェネリックハンドラーまたはWebサービスを作成します(必要な関数の数に応じて)

public class LoadStates : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        JavaScriptSerializer json = new JavaScriptSerializer();
        var data = GetData();
        context.Response.ContentType = "application/json";
        context.Response.Write(json.Serialize(new
        {
            data = data.Select(r => new
            {
                StateId = r.ID,
                StateName = r.Name
            })
        }));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

完全を期すために..これは、ashxWebサービスを使用して同じことを実行する方法です。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld()
    {
        var data = GetData();
        return new
        {
            data = data.Select(r => new
            {
                StateId = r.ID,
                StateName = r.Name
            })
        };
    }
}
于 2012-12-26T16:57:47.993 に答える