georgefowler
asked on
C# MVC Razor How to pre-fill textarea box with data from a database
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):
-------------------------- ---------- ---------- ---------- ---------- ---------- -------
-------------------------- ---------- ---------- ---------- ---------- ---------- -------
the Model (Data.cs):
-------------------------- ---------- ---------- ---------- ---------- ---------- -------
-------------------------- ---------- ---------- ---------- ---------- ---------- -------
the Controller (DataController.cs):
-------------------------- ---------- ---------- ---------- ---------- ---------- -------
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>
--------------------------
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; }
}
}
--------------------------
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);
}
}
}
ASKER
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".
"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".
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);
}
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);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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 :-)
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 :-)
with this action the parameter wouldnt be used anyway.
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 ...