ASP.NET MVC2 - 如何创建表单?

发布于 2024-10-13 15:18:25 字数 2226 浏览 2 评论 0原文

如何在 ASP.NET MVC2 中创建表单,将数据发送到向数据库添加内容的控制器,然后重定向到主页?您能给我一个在视图中如何完成的示例/片段吗?


由于某种原因,我的表单中有一个错误。代码如下:

AddEvent.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Add Event</h2>
<% using (Html.BeginForm()) { %>

    <div>
        <%= Html.LabelFor(x => x.EventName) %>: 
        <%= Html.TextBoxFor(x => x.EventName) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventDate) %>: 
        <%= Html.TextBoxFor(x => x.EventDate) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventLocation) %>: 
        <%= Html.TextBoxFor(x => x.EventLocation) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventDescription) %>: </br> 
        <%= Html.TextAreaFor(x => x.EventDescription) %>
    </div>

    <input type="submit" value="Submit" />
<% } %>

HomeController.cs

    public ActionResult AddEvent()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AddEvent(Event e)
    {
        e.EventCreatorName = Session["UserName"].ToString();
        DatabaseModels db = new DatabaseModels();
        db.AddEvent(e);

        return RedirectToAction("Index", "Home");
    }

DatabaseModels.cs

    public bool AddEvent(Event e)
    {
        anEvent eventToAdd = new anEvent();
        eventToAdd.creator_nickname = e.EventCreatorName;
        eventToAdd.event_category = 1; // TODO
        if (e.EventDate == null)
        {
            eventToAdd.event_date = new DateTime();
        }
        else
        {
            eventToAdd.event_date = DateTime.Parse(e.EventDate);
        }
        eventToAdd.event_location = e.EventLocation;
        eventToAdd.event_name = e.EventName;

        m_db.AddToevents(eventToAdd);
        m_db.SaveChanges();
        return true;
    }

我在表单中输入详细信息,但出现以下异常:

该属性不能设置为空值。

event_location 上。有人能帮忙解决这个问题吗?

How can I create a form in ASP.NET MVC2, send the data to a controller that adds something to the database and then redirects to the home page? Can you give me an example/snippet of how it's done in the View?


For some reason, I have a bug in my form. Here's the code:

AddEvent.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Add Event</h2>
<% using (Html.BeginForm()) { %>

    <div>
        <%= Html.LabelFor(x => x.EventName) %>: 
        <%= Html.TextBoxFor(x => x.EventName) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventDate) %>: 
        <%= Html.TextBoxFor(x => x.EventDate) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventLocation) %>: 
        <%= Html.TextBoxFor(x => x.EventLocation) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.EventDescription) %>: </br> 
        <%= Html.TextAreaFor(x => x.EventDescription) %>
    </div>

    <input type="submit" value="Submit" />
<% } %>

HomeController.cs

    public ActionResult AddEvent()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AddEvent(Event e)
    {
        e.EventCreatorName = Session["UserName"].ToString();
        DatabaseModels db = new DatabaseModels();
        db.AddEvent(e);

        return RedirectToAction("Index", "Home");
    }

DatabaseModels.cs

    public bool AddEvent(Event e)
    {
        anEvent eventToAdd = new anEvent();
        eventToAdd.creator_nickname = e.EventCreatorName;
        eventToAdd.event_category = 1; // TODO
        if (e.EventDate == null)
        {
            eventToAdd.event_date = new DateTime();
        }
        else
        {
            eventToAdd.event_date = DateTime.Parse(e.EventDate);
        }
        eventToAdd.event_location = e.EventLocation;
        eventToAdd.event_name = e.EventName;

        m_db.AddToevents(eventToAdd);
        m_db.SaveChanges();
        return true;
    }

I type in details in the form and I get the following Exception:

This property cannot be set to a null value.

on event_location. Can anyone help solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓦然回首 2024-10-20 15:18:25

asp.net/mvc 站点包含大量值得阅读的有关 MVC 的示例、视频和教程。以下是如何实现您所询问的场景的示例:

模型:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

控制器:

public class PersonsController: Controller
{
    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    public ActionResult Index(Person person)
    {
        // The person object here will have it's FirstName
        // and LastName properties bound to whatever values
        // the user entered in the corresponding textboxes in the form

        // TODO: save person to database 

        // redirect to /home/index
        return RedirectToAction("index", "home");
    }
}

视图:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<AppName.Models.Person>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm()) { %>
        <div>
            <%= Html.LabelFor(x => x.FirstName) %>:
            <%= Html.TextBoxFor(x => x.FirstName) %>
        </div>

        <div>
            <%= Html.LabelFor(x => x.LastName) %>:
            <%= Html.TextBoxFor(x => x.LastName) %>
        </div>

        <input type="submit" value="Save" />
    <% } %>
</asp:Content>

现在您可能想知道 TODO 部分。通常我创建一个存储库来将数据访问逻辑与控制器分离:

public interface IPersonsRepository
{
    void Save(Person person);
}

然后使用该存储库的构造函数注入到我的控制器中:

public class PersonsController: Controller
{
    private readonly IPersonsRepository _repository;
    public PersonsController(IPersonsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    public ActionResult Index(Person person)
    {
        // The person object here will have it's FirstName
        // and LastName properties bound to whatever values
        // the user entered in the corresponding textboxes in the form

        // save person to database 
        _repository.Save(person);

        // redirect to /home/index
        return RedirectToAction("index", "home");
    }
}

显然现在剩下的最后一部分是该存储库的实现。这将取决于您的数据存储方式/位置以及您将使用的特定数据访问技术。那么您是否使用关系数据库、平面文本文件、XML 文件、对象数据库、存储在云上的某些数据库……您将如何访问它们:EF、NHibernate、Linq-to-XML、一些 REST API、 ...

一旦您做出选择,您只需实现该接口并指示您的 DI 框架将正确的实现传递给控制器​​构造函数。

The asp.net/mvc site contains numerous examples, videos and tutorials about MVC that are worth reading. Here's an example of how the scenario you are asking about could be implemented:

Model:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Controller:

public class PersonsController: Controller
{
    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    public ActionResult Index(Person person)
    {
        // The person object here will have it's FirstName
        // and LastName properties bound to whatever values
        // the user entered in the corresponding textboxes in the form

        // TODO: save person to database 

        // redirect to /home/index
        return RedirectToAction("index", "home");
    }
}

View:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<AppName.Models.Person>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm()) { %>
        <div>
            <%= Html.LabelFor(x => x.FirstName) %>:
            <%= Html.TextBoxFor(x => x.FirstName) %>
        </div>

        <div>
            <%= Html.LabelFor(x => x.LastName) %>:
            <%= Html.TextBoxFor(x => x.LastName) %>
        </div>

        <input type="submit" value="Save" />
    <% } %>
</asp:Content>

Now you might be wondering about the TODO part. Usually I create a repository to decouple my data access logic from my controller:

public interface IPersonsRepository
{
    void Save(Person person);
}

and then use constructor injection of this repository into my controller:

public class PersonsController: Controller
{
    private readonly IPersonsRepository _repository;
    public PersonsController(IPersonsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    public ActionResult Index(Person person)
    {
        // The person object here will have it's FirstName
        // and LastName properties bound to whatever values
        // the user entered in the corresponding textboxes in the form

        // save person to database 
        _repository.Save(person);

        // redirect to /home/index
        return RedirectToAction("index", "home");
    }
}

Obviously now the last part that's left is the implementation of this repository. This will depend on how/where your data is stored and the particular data access technology you would be using. So are you using a relational database, flat text file, XML file, object database, some database stored on the cloud, ... how are you going to access it: EF, NHibernate, Linq-to-XML, some REST API, ...

Once you make your choice you simply implement the interface and instruct your DI framework to pass the proper implementation to the controller constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文