Solved

Assign Tempdata to textbox

Posted on 2015-01-05
8
720 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Business Impact of IT Communications

What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

Question has a verified solution.

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

Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
Australian government abolished Visa 457 earlier this April and this article describes how this decision might affect Australian IT scene and IT experts.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

740 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