0

I am using a create form with asp.net mvc 3, where a user enters information and submits, to save their typed information to a database. I would like to display to the user the Id generated with the database row they have just created (via a view for form submitted successfully your id number is...). Does anyone know of a method to accomplish this?

4

2 回答 2

1

您的问题需要更多细节,但是在提出数据持久性策略时应该考虑一些事项。如果您使用的是 Asp.Net Membership 提供程序,您还需要指定它。正如 Bildr 指出的那样,有一些返回用户信息的方法,但我不建议使用该提供程序,除非您需要,因为它正在被 MVC4 中的“简单成员资格提供程序”替换。

如果您使用存储库模式,则可以让类从公共接口继承。当您添加 T 类型的实体时,它会将该实体返回给用户,而当您执行保存时它不会。当您跨越边界时,这种方法会派上用场,例如使用 WCF 服务,并且您要传入具有多个子对象的复杂对象图。当然,您可以更灵活一点,让您的保存方法简单地返回创建对象的 ID。

 public interface IRepository<T>
{
    /// <summary>
    /// Saves the specified object and returns it back to the user.
    /// </summary>
    /// <param name="model">The model.</param>
    /// <returns>The created class</returns>
    T Add(T model);
    /// <summary>
    /// Persist the specified object.
    /// </summary>
    /// <param name="model">The model.</param>
    void Save(T model);
}

当然,如果您正在构建一个更简单的应用程序,并且您像 Jimmy Bogard 一样使用存储库,并且使用 ORM,例如 EntityFramework,那么您可以将您的对象(同样,它是通过引用)传递给您的上下文对象:

  var foo = new Foo{ Name="goo"}
  _modelContext.MyDBSetFoos.Add(foo);
  ((ModelContext)_modelContext).SaveChanges();
  return foo.Id;

如果您澄清您的问题,我很乐意提供更多细节。祝你好运!

于 2012-11-09T16:58:52.963 回答
0

我假设您正在使用表单身份验证,并且您能够保留新用户的名称。将用户名传递给成功控制器,并让它使用FindUsersByName 方法填充模型。

于 2012-11-09T16:23:27.260 回答