Solved

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

Posted on 2012-03-22
6
12,084 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
[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
  • 2
6 Comments
 
LVL 22

Expert Comment

by:ambience
ID: 37756344
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
ID: 37756395
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
ID: 37756988
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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
LVL 22

Accepted Solution

by:
ambience earned 500 total points
ID: 37757001
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
ID: 37757137
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
ID: 37757400
with this action the parameter wouldnt be used anyway.
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
The purpose of this video is to demonstrate how to make a WordPress Site faster and smaller in size by cleaning up the database. This will be demonstrated using a Windows 8 PC. Plugin WP Optimize will be used. Go to your WordPress login page. T…
The purpose of this video is to demonstrate how to manually back up a WordPress Database. This will be demonstrated using a Windows 8 PC. The Host used will be IPage.com Log into your Hosting account. IPage will be used for demonstration : Locat…

690 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