Solved

C# MVC Razor How to pre-fill textarea box with data from a database

Posted on 2012-03-22
6
11,669 Views
Last Modified: 2012-03-23
I have a small website with a Homepage which displays x2 paragraphs of text. These paragraphs are populated from a single record in a database containing 3 fields "ID", "para1" and "para2" (paragraph 1 uses "para1" and paragraph 2 uses "para2"). This record is updated from a different page (called "update") via a form which contains x2 textareas (assigned to update "para1" and "para2"). This allows me to type into the textarea, click "update" and then the two paragraphs on the Homepage will update to reflect the new text.

To navigate to the form page that contains the textareas from the homepage I click an "admin" link which takes me to a logon page, I enter username and password and click "login" and this forwards me on to the "update" page.

What I'd like, is to have the x2 textarea inputs to be pre-populated with the data stored in the "para1" and "para2" fields in the database table. This way, if someone wanted to make a minor edit to either of the paragraphs on the homepage  then they won't need to re-type the whole thing from scratch as the textarea will contain what is currently being displayed.

I'm using C# Razor in Microsoft Visual Web Developer 2010 Express. I am a total beginner at not just this, but any form of development work, so I'm learning as I'm going, please be gentle - I appreciate there will be mistakes / incorrect methods of doing / naming things in the code below, this has all been adapted from a C# MVC tutorial available on ASP.net website, and I'm unsure as how some parts should be put together. Please be gentle :-)

Code examples below:

-----------------------------------------------------------------------------------
the View page (update.cshtml):
-----------------------------------------------------------------------------------
 
@model DFAccountancy.Models.Data
    
    @{
        ViewBag.Title = "Update";
    }
    
    <h2>Update</h2>
    
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">            </script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"     type="text/javascript"></script>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Data</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.para1)
            </div>
            <div class="editor-field">
                @Html.TextAreaFor(model => model.para1, new { cols = 75, @rows = 5 })
                @*@Html.EditorFor(model => model.para1)*@
                @Html.ValidationMessageFor(model => model.para1)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.para2)
            </div>
            <div class="editor-field">
                @Html.TextAreaFor(model => model.para2, new { cols = 75, @rows = 5 })
                @*@Html.EditorFor(model => model.para2)*@
                @Html.ValidationMessageFor(model => model.para2)
            </div>
    
            <p>
                <input type="submit" value="Update" />
            </p>
        </fieldset>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

Open in new window


-----------------------------------------------------------------------------------
the Model (Data.cs):
-----------------------------------------------------------------------------------
 
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;

    namespace DFAccountancy.Models
    {
        public class Data
        {
            [DataType(DataType.MultilineText)]
            public int ID { get; set; }
            public string para1 { get; set; }
            public string para2 { get; set; }
        }
    
        public class DataDBContext : DbContext
        {
            public DbSet<Data> Data { get; set; }
        }
    }

Open in new window


-----------------------------------------------------------------------------------
the Controller (DataController.cs):
-----------------------------------------------------------------------------------
using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using DFAccountancy.Models;
    
    namespace DFAccountancy.Controllers
    { 
        public class DataController : Controller
        {
            private DataDBContext db = new DataDBContext();
    
            //
            // GET: /Data/
    
            public ViewResult Index()
            {
                return View(db.Data.ToList());
            }
    
            //
            // GET: /Data/Details

            public ViewResult Details(string id)
            {
                Data data = db.Data.Find(id);
                return View(data);
            }
          
            //
            // GET: /Data/Update
    
            public ActionResult Update()
            {
                return View();
            } 

            //
            // POST: /Data/Update

            [HttpPost]
            public ActionResult Update(Data data)
            {
                if (ModelState.IsValid)
                {
                    data.ID = 1; //EF need to know which row to update in the database.
                    db.Entry(data).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                return View(data);
            }

        }
    }

Open in new window

0
Comment
Question by:georgefowler
  • 4
  • 2
6 Comments
 
LVL 22

Expert Comment

by:ambience
Comment Utility
OK that should be simple - just pass id of the post to the Update(). Check if the id is passed as parameter then pass the view instance of model fetched from db. Of course, you'll have to update links elsewhere and include post id as parameter if you want the Update to pre-populate.

If you want to force the Update() to always take a parameter then change the type from int? to int and that would make is a required parameter.

            public ActionResult Update(int? id)
            {
                if(id.HasValue) {
                        var model = db.Data.Find(id.Value);
                        return View(model);
               }
               return View();
            }

            //
            // POST: /Data/Update

            [HttpPost]
            public ActionResult Update(Data data)
            {
                if (ModelState.IsValid)
                {
                    data.ID = 1; //EF need to know which row to update in the database.
                    db.Entry(data).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                return View(data);
            }

Hope this helps ...
0
 

Author Comment

by:georgefowler
Comment Utility
Thank you for the help so far. Would you be able to elaborate on the bit below please?

"Of course, you'll have to update links elsewhere and include post id as parameter if you want the Update to pre-populate."

I've added in the code above, sadly doesn't pre-populate, but as I've not completed the sentence above yet maybe it shouldn't be working yet...

Because there is only ever going to be one record in the database, would it be possible to hard code the ID number to it always gets that specific ID? the ID number will always be "1".
0
 
LVL 22

Expert Comment

by:ambience
Comment Utility
Unfortunately I cant beacuse I dont know how you are navigating to the page that has the text areas.

You said you want to populate from database, then you need the ID of the record to load the data from. Either pass that ID as URL parameter like

http://mysite.com/Post/Update?id=1

>> you'll have to update links elsewhere and include post id as parameter if you want the Update to pre-populate

All this meant is that you add the id=1 parameter to the URL That you use to navigate to the update page. I suspect you'd be redirecting from login page, or the user could be clicking a link that takes to that page. This parameter must be added to these urls.

>> I've added in the code above, sadly doesn't pre-populate, but as I've not completed the sentence above yet maybe it shouldn't be working yet...

Yes, because the id parameter would be null and therefore it wont fetch from database.

NOTE: If you really dont want to include the id there then there are various approaches

- Hardcode a default in code

            public ActionResult Update(int? id)
            {
                if(id.HasValue) {
                       id = 1;
               }
               var model = db.Data.Find(id.Value);
               return View(model);
            }

- Supply an in mem model (possibly set defaults in web.config)

            public ActionResult Update(int? id)
            {
               var model = new Data{
                   Id = 1,
                   Text1 = Settings.DefaultText1,
                   Text2 = Settings.DefaultText2
               };
               return View(model);
            }

- Use last saved model from database (assume there is a timestamp in the Data entity)

            public ActionResult Update()
            {
               var model = db.Data.OrderByDesc(x => x.SaveDate).FirstOrDefault();
               return View(model);
            }
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 22

Accepted Solution

by:
ambience earned 500 total points
Comment Utility
I'm sorry I didnt read this part

>> Because there is only ever going to be one record in the database, would it be possible to hard code the ID number to it always gets that specific ID? the ID number will always be "1".

Yes then you should do something like (error checking for the case when there is no record in the database omitted)

            public ActionResult Update()
            {
               var model = db.Data.FirstOrDefault();
               return View(model);
            }
0
 

Author Comment

by:georgefowler
Comment Utility
Thank you very much for your help, this bit worked perfectly:

public ActionResult Update()
            {
               var model = db.Data.FirstOrDefault();
               return View(model);
            }

Also, appending the URL "http://localhost:53559/data/update/?id=1" also worked.

(just for reference, I was navigating from the homepage-->Logon (to authenticate) then that return URL is the "Admin" view with the "Update.cshtml" page)

Thanks once again :-)
0
 
LVL 22

Expert Comment

by:ambience
Comment Utility
with this action the parameter wouldnt be used anyway.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The purpose of this video is to demonstrate how to connect a WordPress website to Google Analytics. This will be demonstrated using a Windows 8 PC Go to your WordPress login page. This will look like the following: mywebsite.com/wp-login.php :…
The purpose of this video is to demonstrate how to exclude a particular blog category from the main blog page. This is can be used when a category already has its own tab, or you simply want certain types of posts not to show up on the main blog. …

728 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

10 Experts available now in Live!

Get 1:1 Help Now