1

我有一个非常简单的数据结构,有两个模型。第一个包含 UserName、UserQuestion 和 userLocationID,另一个包含 LocationName 和 LocationID,第一个表中的 locationID 与第二个表的 LocationName 相关。但是我没有指定任何关系。我已经使用此处使用的代码优先方法设置了数据结构。

我想创建一个表单,它有两个文本输入供用户输入他们的姓名和问题,还有一个选择框,其中填充了第二个表中的所有 locationNames。但是我似乎无法创建允许我这样做的模型。我需要制作一个单独的 ViewModel 吗?

有谁知道一个简单的教程来解释如何做到这一点?

我对 MVC 和 dot net 框架还是很陌生。. 我已经看过这个答案,但我似乎无法修改它以满足我的需要。所以抱歉,如果我要求一些非常基本的东西。

4

1 回答 1

0

我可以举一个控制器、一个视图和三个 C# 类的例子。要使用此代码,请在 Visual Studio 中创建一个空的 MVC2 项目并添加对 Entity Framework dll 版本 4.1 的引用。如果您需要关于将这些文件放在哪里的帮助,我推荐Steve Sanderson 的 MVC2 书

public class User
{
    public int ID { get; set; }
    public string UserName { get; set; }
    public string Question { get; set; }

    public virtual Location Category { get; set; }
}

public class Location
{
    public int ID { get; set; }
    public string LocationName { get; set; }
}

存储库

using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;

public class Repository : System.Data.Entity.DbContext
{
    public DbSet<User> User { get; set; }
    public DbSet<Location> Locations { get; set; }

    public Repository()
    {
        this.Database.Connection.ConnectionString = 
            @"Server=.;Database=Test;Integrated Security=SSPI";

        if (!this.Database.Exists())
        {
            this.Database.Create();
            this.Locations.Add(new Location { LocationName = "Queensway" });
            this.Locations.Add(new Location { LocationName = "Shepherds Bush" }); 
            this.SaveChanges();
        }
    }

    public IEnumerable<Location> GetLocations()
    {
        return this.Locations.Where(x => x.ID > -1);
    }

    public Location GetLocation(int id)
    {
        return this.Locations.First(x => x.ID == id);
    }

    public void SaveUser(User user)
    {
        this.User.Add(user);
        this.SaveChanges();
    }
}

控制器\HomeContoller.cs:

using System.Web.Mvc;

public class HomeController : Controller
{
    Repository repo = new Repository();

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(User user, int categoryId)
    {
        user.Category = repo.GetLocation(categoryId);
        repo.SaveUser(user);
        return View();
    }
}

视图\主页\Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<User>" %>

<html> 
<body>
    <% using (Html.BeginForm())
       {%>
    Username: <%: Html.TextBoxFor(model => model.UserName) %><br />
    Question: <%: Html.TextBoxFor(model => model.Question) %><br />
    Location: <select name="categoryId">
        <% foreach (var location in new Repository().GetLocations())
           {%>
        <option value="<%= location.ID %>">
            <%= location.LocationName %></option>
        <%} %>
    <br />
    </select>
    <p>
        <input type="submit" value="Create" />
    </p>
    <% } %>
</body>
</html>
于 2011-06-29T20:01:15.203 回答