开发者

Getting Username from UserID in MVC3

开发者 https://www.devze.com 2023-03-11 03:30 出处:网络
I have class post: public class Post { [Key] public int PostID { get; set; } [DisplayName(\"Text komentáře\")]

I have class post:

public class Post
{
    [Key]
    public int PostID { get; set; }
    [DisplayName("Text komentáře")]
    [Required(ErrorMessage = "Je potřeba vyplnit text komentáře")]
    public string Text { get; set; }
    public DateTime PostDate { get; set; }

    public int TopicID { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
}

and user class:

public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public FullName Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public IIdentity Identity{ get; set; }
    public virtual Role Right { get; set; }

   public virtual ICollection<Post> Posts { get; set; }
   public virtual ICollection<Topic> Topics { get; set; }
}

topic class:

public class Topic
{
    public int TopicID { get; set; }

    [Required(ErrorMessage = "Je potřeba vyplnit titulek")]
    [DisplayName("Titulek")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Je potřeba vyplnit obsah příspěvku")]
    [DataType(DataType.MultilineText)]
    [DisplayName("Obsah článku")]
    public string Text { get; set; }

    public int UserID { get; set; }
    public virtual User User { get; set; }
    // tento atribut nám nastaví jméno atribut, které bude na stránce
    [DisplayName("Datum zveřejnění")]
    public DateTime PublishedDate { get; set; }

    public virtual ICollecti开发者_C百科on<Post> Posts { get; set; }

}

in controller I have this method for showing topic:

    public ActionResult Zobrazit(int id)
    {
        var topic = db.Topics.Find(id);
        var username = db.Users.Find(topic.UserID).UserName;
        ViewBag.UserName = username;
        return View(topic);
    }

and view for Zobrazit looks like this:

<div class="topicHeader">@Html.DisplayFor(model => model.Title)</div>
   <fieldset>
   <p>Autor: @Html.ActionLink((string)ViewBag.UserName, "Podrobnosti", "Uzivatel", new { id = Model.UserID }, null)
   Zasláno: @Html.DisplayFor(model => model.PublishedDate)</p>
   <p>@Html.DisplayFor(model => model.Text)</p>
   </fieldset>
@if (Model.Posts != null)
{
    foreach (SkMoravanSvitavka.Models.Post comment in Model.Posts)
    {
    @Html.Partial("_Post", comment)
    }
}
@if (Context.User.Identity.IsAuthenticated)
{
    using (Html.BeginForm("Vytvorit", "Post"))
    {
    <div id="posts">
        <input type="hidden" name="TopicID" value="@Model.TopicID" />
        @*<label for="Author">Email:</label> <input type="text" name="Author"/> *@
        <label for="Text">
            Komentář:</label>
        <br />
        <textarea name="Text" rows="5" cols="40"></textarea>
        <br />
        <input type="submit" value="Přidat komentář" />
    </div>
    }
}

and final, partial view for post looks like this:

@model SkMoravanSvitavka.Models.Post
<fieldset>
<p>
Author: @Html.ActionLink((string)ViewBag.UserName, "Podrobnosti", "Uzivatel", new { id = Model.AuthorID }, null) Přidáno: @String.Format("{0:g}", Model.PostDate)
</p>
<p> 
@Model.Text
</p>  
</fieldset>

My problem is that I have in database for each post save UserID and I can get it in controller for topic (lets say I have forum) and I "send" it in ViewBag but I don´t know how to get username in partial view for post from UserID. Thanks for help

Edit: I made changes which were in Eranga post (add public virtual user user, add modelbuilder, ...) but now I have problem with recreating database. In VS there is error:

The database creation succeeded, but the creation of the database objects did not. See inner exception for more details.

And then YSOD:

System.Data.SqlServerCe.SqlCeException: The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = Topic_User ]

Edit2: I change class for post, topic and user a both are showen up in original post and here I added database context:

public class TeamContext : DbContext
{
    public DbSet<Player> Players { get; set; }
    public DbSet<Team> Teams { get; set; }
    public DbSet<New> News { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Topic> Topics { get; set; }
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>().HasRequired(p => p.User)
            .WithMany(u => u.Posts)
            .HasForeignKey(p => p.UserID);
        modelBuilder.Entity<Topic>().HasRequired(t => t.User)
            .WithMany(u => u.Topics)
            .HasForeignKey(t => t.UserID);
    }
  }


You can do something like this.

Add a User property to your Post class

public class Post
{
   //all other fields
   public int UserID { get; set; }
   public User User { get; set; }
}

public class User
{
   //all other fields
   public int UserID { get; set; }
   public virtual ICollection<Post> Posts { get; set; }
}

Then build your model by including the relationship

modelBuilder.Entity<Post>().HasRequired(p => p.User)
                .WithMany(u => u.Posts)
                .HasForeignKey(p => p.UserID);

Then you can access the UserName property in Post objects.

Make sure you eager load 'Posts' property of 'Topic' class and 'User' property of 'Post' class


As you have a UserID property in your Post Model you should be able to do something like this:

@Html.ActionLink(Model.UserID, "Podrobnosti", "Uzivatel" ...

Hope this helps!

UPDATE: Sorry, I didn't read your post well. If you add a User Property to your Post class you will be able to access the property from the partial view like this:

@Html.ActionLink(Model.User.Username, "Podrobnosti", "Uzivatel" ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号