Solved

Assign Tempdata to textbox

Posted on 2015-01-05
8
548 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:dizzycat
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
DLL in ASP.NET 20 38
Angular JS form 8 24
Image(7) 1 33
VB.NET HttpWebRequest 12 30
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now