0

嗨,我正在使用 nhibernate 在 MVC 中开发应用程序。这是一个问答论坛,在第一页上,问题列表显示为链接。现在,当我单击该链接时,它会移动到答案页面,其中显示特定问题的答案。我有两个包含以下字段的表

问题表:

QuestionID int
Question nvarchar(255)
Created_Date datetime
Modified_Date datetime
Created_By int
Modified_By int
Deleted nchar(1)

答案表:

AnswerId int
Answer nvarchar(255)
Created_Date datetime 
Modified_Date datetime  
Created_By int 
Modified_By  int
QuestionID int (foreign key)
Deleted  nchar(1)

这是我尝试过的: Inside QuestionPage.cshtml

@using (Html.BeginForm("Question_Page","QuestionAnswer",FormMethod.Post))
{ 
@Html.ValidationSummary(true) 
<ul>
@foreach (var item in Model)
{
    <li>@Html.ActionLink(item.Question, "Answer_Page", new { Id = item.QuestionID, Question = item.Question })</li>
}
   </ul>

 <br />
<h2><label for="PostyourQuestion:">Post your Question:</label></h2>
 @Html.TextArea("PostyourQuestion")    
<br /><br />
<input type="submit"/>

}

控制器内部:

 public ActionResult Answer_Page(int Id, string Question)
   {
       var model = new AnswerService().GetAllAnswers();
       ViewBag.Question = Question;
       model = (from x in model
                where x.QuestionID.Equals(Id)
                select x).ToList();   

       return View(model);
   }
    [HttpPost]
   public ActionResult Answer_Page(Answers ans, string PostyourAnswer, int Id,string Question)
    {
        ViewBag.Question =Question;
        ans.Answer = PostyourAnswer;
        ans.CreatedDate = DateTime.Now;
        ans.ModifiedDate = DateTime.Now;
        ans.CreatedBy = 101;
        ans.ModifiedBy = 101;
        ans.FkQuestionID= Id;
        if (ModelState.IsValid)
        {
            new AnswerService().SaveOrUpdateAnswers(ans);
            var model = new AnswerService().GetAllAnswers();
            model = (from x in model
                     where x.QuestionID.Equals(Id)
                     select x).ToList();
            return View(model);
        }

        return View();
    }

但问题是 OnPost 我在 Question 变量中得到一个空值,因此当用户提交表单时我无法在帖子上显示问题。请帮助我。我知道我错过了一些愚蠢的东西。

4

2 回答 2

0

尝试更改为

@Html.ActionLink(item.Question, "Answer_Page","QuestionAnswer", new { @Id = item.QuestionID, @Question = item.Question },null)

现在您应该能够在 Question 变量中得到它。

就我个人而言,我认为传递查询字符串中的问题并不是一个好主意。我相信查询字符串有字符限制。理想情况下,您应该只传递问题 ID,并通过查询持久数据源在您的操作方法中再次构建问题对象。

查询字符串的最大可能长度是多少?

http://classicasp.aspfaq.com/forms/what-is-the-limit-on-querystring/get/url-parameters.html

于 2012-03-25T12:52:28.057 回答
0

有几种方法可以处理这个问题。IMO 最好的方法是将问题 id 编码到 url 中,然后再次从您的存储库中获取问题。如果需要更高的性能,在您的存储库中实施缓存,或者作为包装存储库的层。另一种方法是使用 TempData(本质上是 Session)在一个请求周期内保存数据。这种方法有一些失败模式——例如,他们点击页面上的另一个动作然后使用他们的后退按钮——但也相对简单。您不想使用 ViewBag。ViewBag 旨在将辅助数据作为单向传输传递给视图。正如您所发现的,它不会在请求周期内保持其价值。

FWIW,我认为您应该在两种方法中都使用问题ID,而不是将问题本身作为查询字符串的一部分传递。

于 2012-03-25T13:09:29.987 回答