简体   繁体   English

在 C# 中将 GridView 与 MVC 5 中的数据库绑定,我有 ajax JavaScript

[英]Bind GridView With Database In MVC 5 In C# and i have ajax JavaScript

I have problem with create grid (without kendo) I try to make a dictionary.我在创建网格时遇到问题(没有剑道)我尝试制作一本字典。 I have a list of word and pass this to ajax JavaScript and show it to grid in view.我有一个单词列表并将其传递给 ajax JavaScript 并将其显示在视图中的网格中。 but I don't know how to work with this:(. thanks all但我不知道如何处理这个:(。谢谢大家

this is my controller这是我的 controller

public ActionResult ChekingInBank(string username, string password, string datasource, string bnkname, string SqlQuery)
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder["Server"] = datasource;
    builder["Connect Timeout"] = 1000;
    builder["Trusted_Connection"] = true;
    builder["Integrated Security"] = false;
    builder.InitialCatalog = bnkname;
    builder.Password = password;
    builder.UserID = username;
   
     List<TranslateViewModel>  translateViewList = new List< TranslateViewModel>();
    WebGrid TranslateGrid = new WebGrid();
   
    using (SqlConnection con = new SqlConnection(builder.ConnectionString))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(SqlQuery, con))
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    TranslateViewModel translateView = new TranslateViewModel();
                    translateView.id = dr[0].ToString();
                    translateView.word = dr[1].ToString();
                    translateView.translate = dr[2].ToString();

                    translateViewList.Add(translateView);

                }
                if (translateViewList.Count>0)
                {
                    return Json( new {translateViewList = translateViewList, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("No Record Found");
                }
               
               
            }
           
           
        }
    }
}

JavaScript JavaScript

function chekingInBank() {
    var translate = $("#eWord").val();
    var bnkname = $("#combo").val();
    var username = $("#Username").val().trim();
    var password = $("#password").val();
    var datasource = $("#Datasource").val();
    var SqlQuery = "select * from lego.LocalizationView  where Word =N'" + translate + "'";
    if (bnkname) {
        $.ajax({
            url: 'Home/chekingInBank?' + "Username=" + username + "&Password=" + password + "&databaseConString=" + datasource + "&bnkname=" + bnkname,
            data: {
                bnkname: bnkname,
                username: username,
                password: password,
                datasource: datasource,
                SqlQuery: SqlQuery
            },
            //dataType: "json",
            type: "get",
            datatype: "json",
            traditional: true,
            success: function (data)
            {
             
               `I have problem with this `
                debugger;
                if (data != "No Record Found") {
                     $('#gridContent').html(data);
                }
                else {
                   alert('No Record Found')
                    
                }
            },
              
        });

    }
    else
    {
        //do nothing
    }
}

and my view和我的看法

and this:(((还有这个:(((

@{

    var grid = new WebGrid(VeiwModeList, canPage: true, rowsPerPage: 5,
                      selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
    grid.Pager(WebGridPagerModes.All);

}
@grid.GetHtml(
tableStyle: "webGrid",
columns: new[]
{
    grid.Column("id"),
    grid.Column("Word"),
    grid.Column("Translate")
});

First of all, you should never send such data like database's username, password, database name and SQL query from javascript to server.首先,你不应该从 javascript 向服务器发送数据库的用户名、密码、数据库名称和 SQL 查询等数据。 This is dangerous because anyone gain access to your database.这很危险,因为任何人都可以访问您的数据库。 For example one can change your query to something like例如,可以将您的查询更改为类似

var SqlQuery = "TRUNCATE TABLE lego.LocalizationView"

and your server code will execute this destructive query.并且您的服务器代码将执行此破坏性查询。

Next, I think you have some misunderstanding with using WebGrid.其次,我认为您对使用 WebGrid 有一些误解。 For example, your controller's method returns JSON, but in js code you put this JSON as html into HTML element:例如,您的控制器方法返回 JSON,但在 js 代码中,您将此 JSON 作为 html 放入 HTML 元素中:

$('#gridContent').html(data);

Also you didn't mention whether your controller action is decorated with HttpGet attribute.你也没有提到你的 controller 动作是否用 HttpGet 属性装饰。

I advise you to find and implement (reproduce) a working example of using WebGrid with AJAX requests, for example what I've googled: link我建议您找到并实施(复制)一个使用 WebGrid 处理 AJAX 请求的工作示例,例如我用谷歌搜索的内容: 链接

In this example Entity Framework is used to connect to data, but you can begin with returning static JSON in your controller method, to verify this all works altogether:在此示例中,实体框架用于连接到数据,但您可以从在 controller 方法中返回 static JSON 开始,以验证这是否全部有效:

[HttpPost]
public JsonResult AjaxMethod(int pageIndex)
{
    CustomerModel model = new CustomerModel();
    model.PageIndex = pageIndex;
    model.PageSize = 10;
    model.RecordCount = 2; //number of records - for pager
    int startIndex = (pageIndex - 1) * model.PageSize;
    model.Customers = new List<Customer> //some random static data
    {
        new Customer
        {
            CustomerID = "AAAA",
            City = "City 1",
            ContactName = "Contact Name 1",
            Country = "Country 1"
        },
        new Customer
        {
            CustomerID = "BBBB",
            City = "City 2",
            ContactName = "Contact Name 2",
            Country = "Country 2"
        }//, add some more dummy customer's info
    };

    return Json(model);
}

And when you'll reproduce it you can change the CustomerModel to your class, change POST to GET, connect to your database, modify grid columns and so on.当您重现它时,您可以将 CustomerModel 更改为您的 class,将 POST 更改为 GET,连接到您的数据库,修改网格列等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM