Solved

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

Posted on 2012-03-22
6
11,832 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
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 SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
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

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
send messages to whatsapp programatically 2 48
Video Player 11 23
asp.net mvc5 6 17
Function after success of Jquery/AJAX action 9 16
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This article provides a case study on how our local youth baseball league deployed a new website, including the platform selection, implementation and benefits to the league.
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 update a WordPress Site’s version. WordPress releases new versions of its software frequently and it is important to update frequently in order to keep your site secure, and to get new WordPress…

810 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