user1274646
user1274646

Reputation: 921

to display a value fetched from database in Html.Actionlink() in mvc3

i am making an application called AskQuestion where in on the first page i have a list of questions as links and below it is a textarea and a post button to post the question. as i write inside the textarea and press the post button it is displayed inside the question list. now i m fetching the posted questions from the database. and i need to display it as a link.. but Html.Actionlink does not support this

this is my Model class:

  public class Question_Page
{

    public virtual int Id { get; set; }
    public virtual string Question_name { get; set; }
    public virtual string Address { get; set; }
    public virtual DateTime Created_Date { get; set; }
    public virtual DateTime Modified_Date { get; set; }
    public virtual int Created_By { get; set; }
    public virtual int Modified_By { get; set; }
    public virtual char Deleted { get; set; }
    public Question_Page()
    {
        this.Deleted='F';
    }
}

This is my view:

@model IEnumerable<Core.Model.Question_Page>

@{
  ViewBag.Title = "Index";
 }
<style type="text/css">
ul
 {
    list-style-type: none;
 }
</style>

<h2>All Questions</h2>
<hr />

@using (Html.BeginForm("Index","Question",FormMethod.Post))
{
 @Html.ValidationSummary(true)
<ul>
foreach (var item in Model) {

    <li>@Html.ActionLink(item.Question_name, "answer", new { id=item.Id   })</li>
}
   </ul>
<label for="PostyourQuestion:">Post your Question:</label><br /><br />
 @Html.TextArea("textID")    

<br />
<input type="submit"/>
}   

But with this i get an error saying "item does not exists in the current context"

i know i can use anchor tag also before this and i tried that too

<ul>
foreach (var item in Model) {

   <li><a href="answer.cshtml">@Html.DisplayFor(modelItem => item.Question_name)</a></li>
}
</ul>

but with it does not identify the url specified in href

please help me

Upvotes: 2

Views: 2256

Answers (2)

Rinat
Rinat

Reputation: 598

I did a sample which looks like yours and I found out that you missed "@" before "foreach"

@foreach (var item in Model) {

Upvotes: 1

cemsazara
cemsazara

Reputation: 1673

The first one with "Html.ActionLink" should work. Problem can be in your Model. If your model returns null then item in this Model will cause error inside foreach loop, you should first check Model null state. I think Html.ActionLink method is very useful in your case. But you should pass argument to identify your question, namely its id. Then you can use something like this:

    foreach (var item in Model) {

    <li>@Html.ActionLink(item.Question_name, "answer",new{id= item.id})</li>
    

    }

Upvotes: 1

Related Questions