从数据库中检索字段,而仿效呢? [英] Retrieve fields from database without emulating them?

查看:82
本文介绍了从数据库中检索字段,而仿效呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC4一个小的测试程序,它允许您选择从下拉菜单项。它采用的Json 的JavaScript (我不熟悉这些的话)。

I have a small test program in ASP.NET MVC4 which allows you to select items from a dropdown menu. It uses Json and JavaScript (I'm not familiar with these at all).

这里的code我此刻的:

Here's the code I have at the moment:

的HomeController

        public ActionResult CountryList()
        {
            IQueryable countries = Country.GetCountries();

            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(
                            countries,
                            "CountryCode",
                            "CountryName"), JsonRequestBehavior.AllowGet
                            );
            }

            return View(countries);
        }

        public ActionResult StateList(string CountryCode)
        {
            IQueryable states = State.GetStates().Where(x => x.CountryCode == CountryCode);

            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                                states,
                                "StateID",
                                "StateName"), JsonRequestBehavior.AllowGet
                            );

            return View(states);
        }

查看

@section scripts { 
    <script type="text/javascript">
        $(function () {
            $.getJSON("/Home/Countries/List", function (data) {
                var items = "<option>---------------------</option>";
                $.each(data, function (i, country) {
                    items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
                });
                $("#Countries").html(items);
            });

            $("#Countries").change(function () {
                $.getJSON("/Home/States/List/" + $("#Countries > option:selected").attr("value"), function (data) {
                    var items = "<option>---------------------</option>";
                    $.each(data, function (i, state) {
                        items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                    });
                    $("#States").html(items);
                });
            });
        });
    </script>
}

<h1>@ViewBag.Title</h1>

@using (Html.BeginForm())
{
    <label for="Countries">Countries</label>
    <select id="Countries" name="Countries"></select>
    <br /><br />
    <label for="States">States</label>
    <select id="States" name="States"></select>
    <br /><br />
    <input type="submit" value="Submit" />
}

终于在模式

国家

    public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }

        public static IQueryable<Country> GetCountries()
        {
            return new List<Country>
            {
                new Country {
                    CountryCode = "CA",
                    CountryName = "Canada"
                },
                new Country{
                    CountryCode = "US",
                    CountryName = "United-States"
                }
            }.AsQueryable();
        }
    }
}

国家

public class State
{
    public string CountryCode { get; set; }
    public int StateID { get; set; }
    public string StateName { get; set; }

    public static IQueryable<State> GetStates()
    {
        return new List<State>
        {
            new State
                {
                    CountryCode = "CA",
                    StateID=1,
                    StateName = "Ontario"
                },
            new State
                {
                    CountryCode = "CA",
                    StateID=2,
                    StateName = "Quebec"
                },
            new State
                {
                    CountryCode = "CA",
                    StateID=3,
                    StateName = "Nova Scotia"

                    // .. and so on

                }.AsQueryable();

        }
    } 
}

我的问题是,:我怎么做一个数据库表这个解决方案的工作?我需要什么,以使同样的下拉工作,从数据库领域呢?没有人有任何有用的教程,他们可以推荐?

My question is: how do I make this solution work with a database table? What do I need to do in order to make this same dropdown work with fields from a database? Does anyone have any useful tutorials that they could recommend?

推荐答案

您需要选择你将如何访问您的数据库。有很多的选择,但我建议你使用某种 ORM 的。这并不容易选择一个ORM了。所以,你需要之前做的一个研究,找到一个适合自己的需求。正如你在评论中写道,你是新来这个,所以我将提供如何国取看起来可能会在不同的ORM的几样。

You need to choose how you will access your database. There are a lot of options, but I recommend you to use some kind of ORM. It's not easy to choose an ORM too. So you will need to do a research before and find one that fits your needs best. As you wrote in comment you are new to this, so I will provide few samples of how fetching of States might look in different ORM's.

小巧玲珑 - 在此使用ORM(SO)站点。

Dapper - ORM used on this (SO) site.

using (var conn = new SqlConnection("CONN_STR"))
{
    IList<State> states = conn
        .Query<State>(
            "select * States where CountryCode = @CountryCode",
            new { CountryCode = countryCode })
        .ToList();
}

正如你可以在这里看到我们只是提供SQL并与参数Object对象,小巧玲珑做所有的事情我们。我们得到的实体名单。

As you can see here we just provide SQL and object with object with parameters and Dapper does all things for us. We get list of entities.

实体框架 - 创建ORM微软。

Entity Framework - ORM created by Microsoft.

IList<State> states = 
    DbContext.States.Where(state => state.CountryCode == countryCode).ToList();

您不需要编写任何SQL可言,我们使用的是纯LINQ的语法。

You don't need to write any SQL at all, we are using pure LINQ syntax.

当然,所有的ORM的都有自己的优点和缺点,如此反复,你需要之前做一个研究。

Of course all ORM's has their pros and cons, so again, you need to do a research before.

修改:看来你有填充选择问题...那么首先你需要为EF创建正确的模型。您可以重用现有的模型,只需添加一些属性:

EDIT: It seems that you have problems with filling selects... Then first you will need to create correct models for EF. You can reuse your existing models, just add some attributes:

[Table("Countries")]
public class Country
{
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
}


[Table("States")]
public class State
{
    [Key]
    public int StateID { get; set; }
    public string StateName { get; set; }
    public string CountryCode { get; set; }
}

属性,你应该使用,当然你真正的表名。然后,你需要创建的DbContext

In Table attribute you should use your real table names of course. Then you need to create DbContext:

public class MyDbContext : DbContext
{
    public DbSet<Country> Countries { get; set; }
    public DbSet<State> States { get; set; }
}

不要忘了指定在web.config中的连接字符串像教程。

Don't forget to specify connection string in web.config like in tutorial.

我简化了获得国家和国家的方法,现在他们只返回JSON:

I simplified methods for getting countries and states and now they return only JSON:

public ActionResult CountryList()
{
    using (var db = new MyDbContext())
    {
        var countries = db.Countries.ToList();
        return Json(
            new SelectList(countries, "CountryCode", "CountryName"), JsonRequestBehavior.AllowGet);
    }
}

public ActionResult StateList(string countryCode)
{
    using (var db = new MyDbContext())
    {
        var states = !string.IsNullOrEmpty(countryCode)
            ? db.States.Where(state => state.CountryCode == countryCode).ToList()
            : new List<State>();
        return Json(
            new SelectList(states, "StateID", "StateName"), JsonRequestBehavior.AllowGet);
    }
}

这是一个好主意,移动DB访问code到不同的类,但我希望你能自己做。

It's a good idea to move DB access code to different class but I hope you can do it yourself.

您在你有一些奇怪的URL的JavaScript所以这里工作的例子:

You had some strange URl's in you javascript so here is working example:

$.getJSON("/Home/CountryList", function (data) {
    // Same code that you have
});

$("#Countries").change(function () {
    $.getJSON("/Home/StateList?countryCode=" + $("#Countries > option:selected").attr("value"), function (data) {
        // Same code that you have
    });
});

这篇关于从数据库中检索字段,而仿效呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆