• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1129
  • Last Modified:

Assign Tempdata to textbox

Hi experts

Using mvc and c# how can I assign a value in my TempData variable to a textbox, heres my code:

@TempData["tempMovieID"]

<div class="editor-label">
@Html.LabelFor(model => model.MovieID)
 </div>
 <div class="editor-field">
  @Html.EditorFor(model => model.MovieID)  // This is the textbox that I want to assign @TempData["tempMovieID"]
  @Html.ValidationMessageFor(model => model.MovieID)
 </div>

I would also like to make the textbox read-only

Hope somebody can help.
0
dizzycat
Asked:
dizzycat
  • 4
  • 4
1 Solution
 
Carl TawnSystems and Integration DeveloperCommented:
If you want to use on of the *For<> helpers then the data needs to be part of the model for the View. Which you could do like:
@model TempDataDictionary

@using (Html.BeginForm())
{
    <div id="container">
        @Html.TextBoxFor(model => model["tempMovieID"])

        @Html.EditorFor(model => model["tempMovieID"])
    </div>
}

Open in new window

But that would rely on the TempDataDictionary being the only model.

If you want to use TempData as well as a custom model then you would need to use one of the simpler helpers:
@using (Html.BeginForm())
{
    <div id="container">
        @Html.TextBox("tempMovieID", @TempData["tempMovieID"])
    </div>
}

Open in new window

0
 
dizzycatAuthor Commented:
What im trying to do is put the MovieID of a movie in a textbox of my Create view based on the Movie I selected in another page, so I already have my model but is there a way to assign the Comments.MovieID in my model to the MovieID For<> helper ?


@model Mvc2Movie Comments.Models.Comments

@{
    ViewBag.Title = "Create";
}

<h4>Add a comment</h4>            

           
<h2></h2>
<h2>@TempData["tempMovieID"]</h2>                                

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Comments</legend>

       
        <div class="editor-label">
           
            @Html.LabelFor(model => model.MovieID
        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.MovieID)
           
            @Html.ValidationMessageFor(model => model ["tempMovieID"])
        </div>
0
 
Carl TawnSystems and Integration DeveloperCommented:
If MovieID is already a property of your model then what you have should work already.  I'm a little confused as to where TempData and tempMovieID come into it.

Although, logically, you wouldn't want to use an editor for the MovieID you would normally put it in a hidden field so it can't be modified by the user - but that is a bit of a side issue.
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
dizzycatAuthor Commented:
Thats exactly what I want to do , put the MovieID in a hidden field, the MovieID is already a property of my model but I cant get it to be displayed when I go to my Create View page, the Model will contain many MovieIDs (but they will all be the same), could this be an issue ?.  The TempData was just a way I was experimenting with to get the MovieID in to the Create View page but from what you have said the correct way to go is to get it from my model.
0
 
Carl TawnSystems and Integration DeveloperCommented:
Is you model actually a collection, rather than a single object? Otherwise i don't quite get why your model would have multiple ID's.

It may be easier if you could post the definition of your model and the controller action that populates the model prior to sending it to the View.
0
 
dizzycatAuthor Commented:
MODEL

public class Comments
    {
        [Key]
        public int CommentsID { get; set; }

        public int MovieID { get; set; }                  

        [Required]
        public string Comment { get; set; }
 }

The Action Result, ive just realised that this action might not be populating the Comments model

[HttpPost]
        public ActionResult Create(Comments comments)                      
        {
            if (ModelState.IsValid)
            {
                //TempData["tempMovieID"] = comments.MovieID;
                //TempData.Keep();
                db.dbsComments.Add(comments);              
                db.SaveChanges();                                
                return RedirectToAction("Index");
            }

            return View(comments);
        }

I have a Linq query which gets data in the index view then the below loop displays that data

@if (Model != null)
{
   
foreach (var item in Model)      

{
   
    <div id="Comments" class="Comments">@item.Comments.Comment@item.Comments.MovieID</div>              
   
}
   
}
<input type="submit" value="Add Comment"/>
0
 
Carl TawnSystems and Integration DeveloperCommented:
If you're doing what i think you're doing then you might want to consider using a ViewModel.
Something similar to the following:
        public ActionResult Index()
        {
            int movieId = 1;        // dummy value - would be passed to the action normally

            // create ViewModel with the existing comments for the movie, and a new empty Comments object
            CommentsViewModel viewModel = new CommentsViewModel();
            viewModel.NewComment = new Comments { MovieID = movieId, CommentID = -1 };
            viewModel.Comments = GetComments(movieId);

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Index(Comments newComment)
        {
            // do something with the comment

            return View();
        }

        private List<Comments> GetComments(int movieId)
        {
            // return dummy test data
            return new List<Comments>
            {
                new Comments { MovieID = 1, CommentID = 1, Comment = "Hello" },
                new Comments { MovieID = 2, CommentID = 2, Comment = "World" }
            };
        }
    }

    // viewmodel - contains existing comments and a new empty Comments object
    public class CommentsViewModel
    {
        public Comments NewComment { get; set; }
        public List<Comments> Comments { get; set; }
    }

    // dummy comments class
    public class Comments
    {
        public int MovieID { get; set; }
        public int CommentID { get; set; }
        public string Comment { get; set; }
    }

Open in new window

With a View along the lines of:
@model MvcApplication1.Controllers.CommentsViewModel

<!-- show existing comments if any -->
@if (Model.Comments.Count > 0)
{
    foreach(var item in Model.Comments)
    {
        <div>@item.Comment</div>
    }
}

<!-- bind the form to our new empty Comment object so it can be posted back -->
@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.NewComment.MovieID)

    <div>
        <span>Comment:</span>
        @Html.TextBoxFor(model => model.NewComment.Comment)
    </div>
    
    <input type="submit" value="Add Comment" />
}

Open in new window

0
 
dizzycatAuthor Commented:
Thanks Carl, I think that I have been going about this the wrong way and creating a view model would defiantly be my best option.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now