Solved

Assign Tempdata to textbox

Posted on 2015-01-05
8
618 Views
Last Modified: 2015-01-06
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
Comment
Question by:dizzycat
  • 4
  • 4
8 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40533158
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
 

Author Comment

by:dizzycat
ID: 40533210
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40533226
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:dizzycat
ID: 40533275
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40533357
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
 

Author Comment

by:dizzycat
ID: 40533413
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
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 40533772
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
 

Author Closing Comment

by:dizzycat
ID: 40533850
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

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

FAQ pages provide a simple way for you to supply and for customers to find answers to the most common questions about your company. Here are six reasons why your company website should have a FAQ page
There’s a good reason for why it’s called a homepage – it closely resembles that of a physical house and the only real difference is that it’s online. Your website’s homepage is where people come to visit you. It’s the family room of your website wh…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question