Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Assign Tempdata to textbox

Posted on 2015-01-05
8
Medium Priority
?
932 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
Understanding Web Applications

Without even knowing it, most of us are using web applications on a daily basis. Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We often confuse these web applications tools for websites.  So, what is the difference?

 

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 2000 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

636 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