I am refactoring somebody else's app written badly in ASP.NET MVC 4 (Razor). [.NET is not my specialty - I do primarily C/C++]. He is not doing database access the MVC canonical way. He is using a Repository class for each table to execute all of his SQL commands on SQL Server rather than the let the basic Entity Framework do the heavy lifting. The app has to:
read a list of rows from a table from the controller (he has a Model for the table).
return this list of model objects to a view (ViewBag or ViewData would be easiest).
insert the list members in a table or list in the View.
select a single row (representing a from the list return the selected row to a controller ActionResult- a single table record in the model class
public List<Note> GetNotesByWorkGroup(string workGroup)
{
List<Note> notes = new List<Note>;
string sql = "SELECT * FROM tblNotes where WorkGroup = 'Foo';
SqlCommand sqlCmd = new SqlCommand(sql, conn);
SqlDataReader myReader = sqlCmd.ExecuteReader();
if (myReader.HasRows)
{
while (myReader.Read())
{
Note note = new Note();
note.NoteId = myReader.GetInt32(NoteIdOrdinal);
note.DateTime = myReader.GetDateTime(DateTimeOrdinal);
note.WrittenBy = myReader.GetString(WrittenByOrdinal);
notes.Add(note);
}
}
return notes;
}
The controller receives this and must pass it to a view. His way of passing the list is:
List<Note> notes = noteRepository.GetNotesByWorkGroup();
ViewData["myList"] = notes;
In the view, he fouled everything up. Simplest solution would be to either create a table or list with an onclick(note.Id) for each element which must be clickable (a button or href?). Each row will need a clickable element and one other text element from the Note object for a two-parm row display.
For example, it would need to look like this, with Date the selectable field and WrittenBy just text.
Date1 WrittenBy
Date2 WrittenBy
Date3 WrittenBy
Then a javascript function can receive the Id onclick() and submit it to the controller ActionResult().
I just need a sample of View code (MVC 4, C#, Razor) showing how the ViewData["myList"] gets dereferenced from C# to HTML and inserted into the rows in the list or table. Also, how would I write a submit in a javascript function that passes a parm?
Any suggestions and examples for the View?