如何将帖子ID从网址传递到另一个页面?

时间:2016-08-09 15:13:37

标签: c# html asp.net-mvc razor

我正在尝试通过创建一个博客网站来学习ASP.NET MVC和C#。我目前有一个包含帖子的页面和个别帖子的详细信息页面,其中包含url中的postId(/ post / details / {id}),我有一个链接,用于发送用户创建评论。出于某种原因,当我将其作为CommentController中Create类的参数附加时,我的帖子ID不会出现。任何有关这方面的帮助将不胜感激。提前致谢!

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

发布详细信息Razor HTML页面:

@model FantaC.Models.Post

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<h2>Details</h2>

<div class="row">
    <div class="col-md-8 whiteBorder scroll">
         <div class="postName">
             <h4>@Html.DisplayFor(model => model.PostName)</h4>
             <h4>Written by: @Html.DisplayFor(model => model.UserName)</h4>
             <img src="@Html.DisplayFor(model => model.PostImage)" />
         </div>
         <div class="postContent">
             <p>@Html.DisplayFor(model => model.PostContent)</p>
         </div>
     </div>
     <div class="col-md-4 whiteBorder scroll">
         <h4>Comments</h4>
         <!--Comments attached to this post-->
         @*@=Html.RenderAction("Create", "Comments", new { postId = Model.PostId });*@
         @*@Html.Partial("AddComment", Model.NewComment)*@
    </div>
</div>
<p>
    @Html.ActionLink("Add a Comment", "Create", "Comment") | @*Redirects to create comment page*@
    @Html.ActionLink("Back to List", "Index")
</p>

评论/创建Razor HTML:

@model FantaC.Models.Comment

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Comment</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.CommentSubject, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CommentSubject, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CommentSubject, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CommentContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CommentContent, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CommentContent, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
             <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
             </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

CommentController.cs:

    // GET: Comment/Create
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(string id, [Bind(Include = "CommentSubject,CommentContent")] Comment model) // string id is null***
    {
        if (ModelState.IsValid)
        {
            ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

            var commentId = (23817 + db.Comment.Count()).ToString().PadLeft(10, '0');

            var comment = new Comment
            {
                CommentId = commentId,
                PostId = id, // id is null because it is null in parameter***
                UserName = user.UserName,
                PostTime = DateTime.Now,
                CommentSubject = model.CommentSubject,
                CommentContent = model.CommentContent
            };

            db.Comment.Add(comment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(model);
    }

1 个答案:

答案 0 :(得分:1)

如果@ADyson的注释不起作用,只需在结尾处添加一个null:

@Html.ActionLink("Add a Comment", "Create", "Comment", new { id= Model.PostId }, null) 

最后一个参数用于html属性,例如maxlength。你正在使用的构造函数是(HtmlHelper,String,String,String,Object,Object),你可以在这里看到更多:https://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink.aspx - Ricardo Pontual