Telerik RadScheduler Datasource - radscheduler

I have the ff code:
// note: entries is a list binded to a query from the database
// wherein i'm passing some parameters to satisfy
// the conditions from the query
foreach (var entry in entries)
{
Appointment appointment = new Appointment();
appointment.Start = entry.StartDateTime;
appointment.End = entry.EndDateTime;
appointment.Summary = entry.Summary;
this.radScheduler.Appointments.Add(appointment);
}
Is there a way to bind the entries directly to radScheduler without using foreach statement?
I've also tried using radScheduler.datasource but it doesn't work.

Please check below code :
.aspx
<telerik:RadScheduler ID="RadScheduler1" runat="server" DataKeyField="ID" DataSubjectField="Subject"
DataStartField="StartDate" DataEndField="EndDate" >
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<MyScedule> lst = new List<MyScedule>();
MyScedule obj = new MyScedule();
obj.ID = 1;
obj.Subject = "my Subject";
obj.StartDate = DateTime.Now;
obj.EndDate = DateTime.Now.AddHours(1);
lst.Add(obj);
MyScedule obj1 = new MyScedule();
obj1.ID = 2;
obj1.Subject = "my Subject";
obj1.StartDate = DateTime.Now.AddHours(2);
obj1.EndDate = DateTime.Now.AddHours(3);
lst.Add(obj1);
RadScheduler1.DataSource = lst;
RadScheduler1.DataBind();
}
}
.cs
public class MyScedule
{
public int ID { get; set; }
public string Subject { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
http://www.telerik.com/help/aspnet-ajax/scheduler-database-structure.html
It worked from my side.

Related

How to add entity referencing two other entities to database to database in ASP.NET CORE

please I have these entities to be sent to database
MatchingChildtoApplicant
{
[Key]
public int MatchId { get; set; }
public int ChildId {get; set;}
public Child Children { get; set; }
public int ApplyId {get; set;}
public ICollection<Application> Applications { get; set; }
public string MatchingBy { get; set; }
}
this is the post request to send to the database
[HttpPost]
public async Task<ActionResult<MatchingChildtoApplicant>> AddNewMatching( int applyid, int chd, [FromForm]MatchingChildtoApplicant matchingChildtoApplicant)
{
//getting the application to match
var gettheapplicantion = await _unitOfWork.ApplicationRepository.GetApplicantByIdAsync(applyid);
if(gettheapplicantion == null){
return NotFound("The Application to match was not found");
}
var appid = gettheapplicantion.ApplyId;
//getting the child to match with applicant
var childtomatch = await _unitOfWork.ChildRepository.GetChildByIdAsync(chd);
if(childtomatch == null){
return NotFound("The child to match was not found");
}
var childtoid = childtomatch.Cld;
//getting the login user doing the matching
var userdoingmatch = await _userManager.FindByEmailFromClaimsPrinciple(User);
if (userdoingmatch == null)
{
return NotFound("The user doing the matching details is missing");
}
var nameofuser = userdoingmatch.DisplayName;
//declaring new instance of MatchingChildtoApplicant
var newmatching = new MatchingChildtoApplicant
{
ApplyId = appid,
ChildId = childtoid,
MatchingBy = nameofuser,
Comment = matchingChildtoApplicant.Comment,
TheApplicationAcepted = matchingChildtoApplicant.TheApplicationAcepted,
MatchedDate = matchingChildtoApplicant.MatchedDate,
};
This is where I get the error sending to the database
// var result = await _context.MatchingChildtoApplicant.AddAsync(matchingChildtoApplicant);
// var result = await _context.MatchingChildtoApplicant.AddAsync(matchingChildtoApplicant);
// gettheapplicantion.MatchingChildtoApplicants.Children.Add(matchingChildtoApplicant);
await _context.SaveChangesAsync();
return new MatchingChildtoApplicant
{
ApplyId = appid,
ChildId = childtoid,
MatchingBy = nameofuser,
Comment = matchingChildtoApplicant.Comment,
TheApplicationAcepted = matchingChildtoApplicant.TheApplicationAcepted,
MatchedDate = matchingChildtoApplicant.MatchedDate,
};
The error I get is this
The type arguments for method 'ValueTransformerConfigurationExtensions.Add(List, Expression<Func<TValue, TValue>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. [API]

ApplicationUser is not saving changes to field after there is already a value in that field

I'm working on a project that keeps track of the hours employees have worked between different crews. The way the app is supposed to work is that an employee submits a Daysheet form that has their clock-in and clock-out time and the id of their Field Manager(FMId). Each Field Manager has a column in the database that should keep track of the DaysheetIds of forms that are submitted with their FMId. The problem is that this column is only saving the first DaysheetId that gets submitted. Once there's a value in that column, the Field Manager doesn't update to add any other DaysheetIds.
To keep my post concise, I'm trying to post only the relevant code, but let me know if I'm missing something that would be important.
Here's the action in my controller where the Field Manager should be updated. I added the var FM just before the return to see what was happening to the Field Manager with the debugger.
public IActionResult Submit(EmployeeDaySheetViewModel employeeDaySheetViewModel)
{
if (ModelState.IsValid)
{
var newDaySheet = new EmployeeDaySheet
{
Id = employeeDaySheetViewModel.DaysheetId,
EmployeeId = employeeDaySheetViewModel.EmployeeId,
EmployeeName = employeeDaySheetViewModel.EmployeeName,
FMId = employeeDaySheetViewModel.FMId,
Date = employeeDaySheetViewModel.Date,
ClockIn = employeeDaySheetViewModel.ClockIn,
ClockOut = employeeDaySheetViewModel.ClockOut,
};
var success = _employeeDaySheetRepository.AddDaySheet(newDaySheet);
if (success)
{
_applicationUserRepository
.AddCrewDaySheetToFieldManager(employeeDaySheetViewModel.FMId,
employeeDaySheetViewModel.DaysheetId);
TempData["UserMessage"] = "Successfully submitted daysheet for " + DateTime.Now.Day.ToString();
}
else
{
TempData["ErrorMessage"] = "Unable to submit daysheet. Please try again in a few minutes.";
}
}
var FM = _applicationUserRepository.GetFieldManagerById(employeeDaySheetViewModel.FMId);
return Redirect("/home/");
Here is the AddCrewDaySheetToFieldManager method in my user repository that's being called in the controller action:
public bool AddCrewDaySheetToFieldManager(string FMId, string DaySheetId)
{
var fieldManager = _applicationDbContext.ApplicationUsers
.FirstOrDefault(u => u.Id == FMId);
if (fieldManager.CrewDaySheetIds != null)
{
var oldCrewIds = fieldManager.CrewDaySheetIds;
// If the user deletes all their crewIds, the database leaves an empty string in their crewIds column.
// Replacing user.crewIds that has "" at index 0 is the same as starting a new list.
if (oldCrewIds[0] == "")
{
var newCrewIds = new List<string> { DaySheetId };
fieldManager.CrewDaySheetIds = newCrewIds;
}
else
{
fieldManager.CrewDaySheetIds.Add(DaySheetId);
}
}
else { fieldManager.CrewDaySheetIds = new List<string> { DaySheetId }; }
_applicationDbContext.SaveChanges();
return true;
This is what my ApplicationUser looks like:
public class ApplicationUser : IdentityUser
{
public string Tier { get; set; }
public bool IsFieldManager { get; set; }
public double HourRate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<string> PayrollObjectIds { get; set; }
public List<string> CrewDaySheetIds { get; set; }
}
In order to convert the lists attributes of this object to strings, I've got this in my DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
var splitStringConverter = new ValueConverter<List<string>, string>(v => string.Join(";", v), v => v.Split(new[] { ';' }).ToList());
builder.Entity<ApplicationUser>().Property(nameof(ApplicationUser.PayrollObjectIds)).HasConversion(splitStringConverter);
builder.Entity<ApplicationUser>().Property(nameof(ApplicationUser.CrewDaySheetIds)).HasConversion(splitStringConverter);
base.OnModelCreating(builder);
//I also seed some data here//
}
What I can't figure out is the point at which the data is not getting saved. When I run the debugger, I can see the fieldManager is getting updated. In the AddCrewDaySheetToFieldManager method, fieldManager.CrewDaySheetIds has the DaysheetId. Then, back in the action, just before return Redirect('/home/')the FM.CrewDaySheetIds still has the DaysheetId. However, when I look at the database or try to access the CrewDaysheetIds on the FM user, only the first DaysheetId is there.
I suspect that there's something going wrong with the splitStringConversion, but I've used the same code in another project and not had this issue, so I'm stuck for what to do.
I didn't understand your question correctly but if you want update or insert some data in your database you can use _applicationDbContext.ApplicationUsers.add(fieldManager); for insert, and _applicationDbContext.Entry(fieldManager).State = EntityState.Modeified; for update. but you didn't use any of them before _applicationDbContext.SaveChanges().
I think you have to write this:
public bool AddCrewDaySheetToFieldManager(string FMId, string DaySheetId)
{
var fieldManager = _applicationDbContext.ApplicationUsers
.FirstOrDefault(u => u.Id == FMId);
if (fieldManager.CrewDaySheetIds != null)
{
var oldCrewIds = fieldManager.CrewDaySheetIds;
// If the user deletes all their crewIds, the database leaves an empty string in their crewIds column.
// Replacing user.crewIds that has "" at index 0 is the same as starting a new list.
if (oldCrewIds[0] == "")
{
var newCrewIds = new List<string> { DaySheetId };
fieldManager.CrewDaySheetIds = newCrewIds;
}
else
{
fieldManager.CrewDaySheetIds.Add(DaySheetId);
}
}
else { fieldManager.CrewDaySheetIds = new List<string> { DaySheetId }; }
_applicationDbContext.entry(fieldManager).State = EntityState.Modified;
_applicationDbContext.SaveChanges();
return true;

BreezeSharp Attach Property key not found

I'm implementing an application with Breezesharp. I ran into a issue when insert the entity in the EntityManager. The error is:
There are no KeyProperties yet defined on EntityType: 'TransportReceipt:#Business.DomainModels'
I already faced this error with my first entity type "Customer" and implement a mismatching approach as suggested here. In that case I made the get operation against my WebApi with success. But now I'm creating the TransportReceipt entity inside my application.
Mapping mismatch fix
public static class ExtendMap
{
private static bool? executed;
public static void Execute(MetadataStore metadataStore) {
if (ExtendMap.executed == true)
{
return;
}
var customerBuilder = new EntityTypeBuilder<Customer>(metadataStore);
customerBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var transportReceiptBuilder = new EntityTypeBuilder<TransportReceipt>(metadataStore);
transportReceiptBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var transportReceiptAttachmentBuilder = new EntityTypeBuilder<TransportReceiptAttachment>(metadataStore);
transportReceiptAttachmentBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var uploadedFileBuilder = new EntityTypeBuilder<UploadedFile>(metadataStore);
uploadedFileBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
ExtendMap.executed = true;
}
}
My base dataservice core code
public abstract class SimpleBaseDataService
{
public static string Metadata { get; protected set; }
public static MetadataStore MetadataStore { get; protected set; }
public string EntityName { get; protected set; }
public string EntityResourceName { get; protected set; }
public EntityManager EntityManager { get; set; }
public string DefaultTargetMethod { get; protected set; }
static SimpleBaseDataService()
{
try
{
var metadata = GetMetadata();
metadata.Wait();
Metadata = metadata.Result;
MetadataStore = BuildMetadataStore();
}
catch (Exception ex)
{
var b = 0;
}
}
public SimpleBaseDataService(Type entityType, string resourceName, string targetMethod = null)
{
var modelType = typeof(Customer);
Configuration.Instance.ProbeAssemblies(ConstantsFactory.BusinessAssembly);
try
{
this.EntityName = entityType.FullName;
this.EntityResourceName = resourceName;
this.DefaultTargetMethod = (string.IsNullOrWhiteSpace(targetMethod) ? "GetAllMobile" : targetMethod);
var dataService = new DataService($"{ConstantsFactory.Get.BreezeHostUrl}{this.EntityResourceName}", new CustomHttpClient());
dataService.HasServerMetadata = false;
this.EntityManager = new EntityManager(dataService, SimpleBaseDataService.MetadataStore);
this.EntityManager.MetadataStore.AllowedMetadataMismatchTypes = MetadataMismatchTypes.AllAllowable;
// Attach an anonymous handler to the MetadataMismatch event
this.EntityManager.MetadataStore.MetadataMismatch += (s, e) =>
{
// Log the mismatch
var message = string.Format("{0} : Type = {1}, Property = {2}, Allow = {3}",
e.MetadataMismatchType, e.StructuralTypeName, e.PropertyName, e.Allow);
// Disallow missing navigation properties on the TodoItem entity type
if (e.MetadataMismatchType == MetadataMismatchTypes.MissingCLRNavigationProperty &&
e.StructuralTypeName.StartsWith("TodoItem"))
{
e.Allow = false;
}
};
}
catch (Exception ex)
{
var b = 0;
}
}
}
This is who I'm trying to add the new entity
//DataService snippet
public void AttachEntity(T entity)
{
this.EntityManager.AttachEntity(entity, EntityState.Added);
}
//Business
this.TransportReceipt = new TransportReceipt { id = Guid.NewGuid(), date = DateTime.Now, customerId = Customer.id/*, customer = this.Customer*/ };
this.Attachments = new List<TransportReceiptAttachment>();
this.TransportReceipt.attachments = this.Attachments;
TransportReceiptDataService.AttachEntity(this.TransportReceipt);
When I try to add add the entity to the EntityManager, I can see the custom mapping for all my entity classes.
So my question is what I'm doing wrong.
Ok. That was weird.
I changed the mapping for a new fake int property and works. I'll test the entire save flow soon and I'll share the result here.
Update
I moved on and start removing Breezesharp. The Breezesharp project is no up-to-date and doesn't have good integration with Xamarin. I'll appreciate any comment with your experience.

asp.net mvc model state errors keys

So I discovered an interesting problem.
I have a model like this:
public class ApplicantModel
{
[Display(Name = "Firstname", ResourceType = typeof(Resources))]
[MaxLength(50, ErrorMessageResourceName = "FirstName", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
[Required(ErrorMessageResourceName = "FirstName", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
public string Firstname { get; set; }
[Display(Name = "Surname", ResourceType = typeof(Resources))]
[MaxLength(50, ErrorMessageResourceName = "Surname", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
[Required(ErrorMessageResourceName = "Surname", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
public string Surname { get; set; }
}
that is all fine, and when I check the Model state and there is an error on a model I get something like this:
errors:
[{
Key = FirstApplicant.Firstname
Value = ["First name is required field"]
},
{
Key = FirstApplicant.Surname
Value = ["Surname name is required field"]
}].
That is also fine.
Edit:
This is the c# ModelState object visualized as JSON object. Real object looks like this:
ModelState
{System.Web.Mvc.ModelStateDictionary}
Count: 2
IsReadOnly: false
IsValid: false
Keys: Count = 2
Values: Count = 2
Results View: Expanding the Results View will enumerate the IEnumerable
However my question is. Is it possible to somehow change the key? I know that the key is created as the name of object and then the name property on that object.
So it makes sense, but is there any way how to change this default behavior? Or do I have to change the names of objects?
Edit2:
What I am trying to achieve here is that I have a c# ViewModel and knockout ViewModel. and when you do server side validations you get this dictionary of keys and values which I serialize and send to client.
And then I call this function on it on client:
var errors = #Html.Raw(Json.Encode(Model.Errors));
function showErrors(serializedErrors) {
var errors = JSON.parse(serializedErrors);
for (var i = 0; i < errors.length; i++) {
var error = errors[i];
var key = error.Key;
var property = eval("masterModel." + key);
property.setError(error.Value.ErrorMessage);
property.isModified(true);
}
}
showErrors(errors);
And this would work fine if the view model property names match on the server and on client. But for example on server side I have a FirstApplicant.FirstName and on a client side it is ApplicantOne.firstname. Thank you all for help and comments. I hope I explained my problem in more detail this time.
in the end I found a solution to this problem. It is a bit complicated but it works.
First I've created an attribute.
public class ClientNameAttribute : Attribute, IMetadataAware
{
public ClientNameAttribute(string name)
{
this.Name = name;
}
public string Name { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["ClientName"] = this.Name;
}
}
Notice that this attribute also implements IMetadataAware
Next step was to create Html helper, so I could call this in a view.
public static class HtmlHelperExtensions
{
public static string CustomModelState<T>(this HtmlHelper<T> helper)
{
var errors = helper.ViewData.ModelState.Select(
m => new { Key = GenerateClientName(m.Key, helper), Value = m.Value.Errors.FirstOrDefault() }).Where(e=> e.Value != null);
return Json.Encode(errors);
}
private static string GenerateClientName<T>(string key, HtmlHelper<T> helper)
{
StringBuilder builder = new StringBuilder();
int periodIndex = -1;
do
{
periodIndex = key.IndexOf('.', periodIndex + 1);
string part = key.Substring(0, periodIndex==-1 ? key.Length : periodIndex);
var partMetadata = ModelMetadata.FromStringExpression(part, helper.ViewData);
object clientName;
if (builder.Length > 0)
{
builder.Append('.');
}
if (partMetadata.AdditionalValues.TryGetValue("ClientName", out clientName))
{
builder.Append(clientName);
}
else
{
builder.Append(partMetadata.PropertyName);
}
}
while (periodIndex != -1);
return builder.ToString();
}
}
CustomModelState is a method that I call in a view.
like this:
var errors = #Html.Raw(Html.CustomModelState());
if (errors.length > 0) {
showErrors("masterModel",errors);
}
this will give you nicely formated errors, with your custom names of properties.
And here are tests for it:
public class TestModel
{
[Required]
public string Normal { get; set; }
[ClientName("Other")]
[Required]
public string Changed { get; set; }
[ClientName("Complicated")]
public TestModelTwo TestModelTwo { get; set; }
}
public class TestModelTwo
{
public string PropertyOne { get; set; }
[ClientName("Two")]
public string PropertyTwo{ get; set; }
}
[TestClass]
public class HtmlHelperExtensionsTests
{
[TestMethod]
public void CustomModelStateTests()
{
var model = new TestModel();
var page = new ViewPage();
page.ViewData.Model = model;
page.ViewData.ModelState.AddModelError("Normal", "Error1");
page.ViewData.ModelState.AddModelError("Changed", "Error2");
HtmlHelper<TestModel> helper = new HtmlHelper<TestModel>(new ViewContext(), page);
var custom = helper.CustomModelState();
string expectedResult =
"[{\"Key\":\"Normal\",\"Value\":{\"Exception\":null,\"ErrorMessage\":\"Error1\"}},{\"Key\":\"Other\",\"Value\":{\"Exception\":null,\"ErrorMessage\":\"Error2\"}}]";
Assert.AreEqual(expectedResult, custom);
}
[TestMethod]
public void CustomModelStateTests_ObjectProperty_With_ClientName()
{
var model = new TestModel();
model.TestModelTwo = new TestModelTwo();
var page = new ViewPage();
page.ViewData.Model = model;
page.ViewData.ModelState.AddModelError("TestModelTwo.PropertyOne", "Error1");
page.ViewData.ModelState.AddModelError("TestModelTwo.PropertyTwo", "Error2");
HtmlHelper<TestModel> helper = new HtmlHelper<TestModel>(new ViewContext(), page);
var custom = helper.CustomModelState();
string expectedResult =
"[{\"Key\":\"Complicated.PropertyOne\",\"Value\":{\"Exception\":null,\"ErrorMessage\":\"Error1\"}},{\"Key\":\"Complicated.Two\",\"Value\":{\"Exception\":null,\"ErrorMessage\":\"Error2\"}}]";
Assert.AreEqual(expectedResult, custom);
}
}

How to return a DataSet to a View

I am sending a standard Sql select statement to my Sql box via the SqlDataAdapter, then populating a DataSet object.
I can access the rows in the resulting DataSet, but how can I convert the DataSet into a List which can be returned to the MVC View. i.e. I'm assuming a List object is the best way to handle this.
Here's my controller c# code:
public class QAController : Controller
{
private readonly static string connString = ConfigurationManager.ConnectionStrings["RegrDBConnection"].ToString();
private readonly static SqlConnection sqlConn = new SqlConnection(connString);
private readonly static SqlCommand sqlComm = new SqlCommand();
public ActionResult Index()
{
DbRegressionExec();
return View();
}
public static void DbRegressionExec()
{
// SELECT TABLE CONTENTS FROM SQL !!
RegressDB_TableList regresDB = new RegressDB_TableList();
string sqlStr = "select * from [RegressionResults].[dbo].[Diff_MasterList] order by TableName";
// POPULATE DATASET OBJECT
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, sqlConn);
da.SelectCommand.CommandType = CommandType.Text;
sqlConn.Open();
try
{
da.Fill(ds, "RegresDB");
}
catch (Exception e)
{
throw;
}
finally
{
sqlConn.Close();
}
// I can iterate thru rows here, but HOW DO CONVERT TO A LIST OBJECT ????
int numRows = ds.Tables["RegresDB"].Rows.Count;
for (int i = 0; i < numRows; i++)
{
string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
}
//List<RegressDB_TableList> masterList = regresDB.RegresTableList.ToList(); //not working !!
//var masterList = regresDB.TableName.ToList(); //
}
}
and a simple class I may need to make this happen:
namespace RegressionMvc.Models
{
public class RegresDB_TableName
{
public string TableName { get; set; }
}
public class RegressDB_TableList
{
public List<RegresDB_TableName> RegresTableList { get; set; }
}
}
In the end, I'm trying to figure out the best way to handle DataSet results from Sql Server and how to make them back to an MVC View.
I can probably go with jQuery and Json, meaning just convert the data fields to Json and return to JQuery, but I'm sure there are several ways to handle Sql based result sets.
Thanks in advance for your advice....
Best,
Bob
In your controller put the code like this
[HttpGet]
public ActionResult View(Modelclass viewmodel)
{
List<Modelclass> employees = new List<Modelclass>();
DataSet ds = viewmodel.GetAllAuthors();
var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Modelclass{
AuthorId = dataRow.Field<int>("AuthorId"),
Fname = dataRow.Field<string>("FName"),
Lname = dataRow.Field<string>("Lname")
});
var list = empList.ToList();
return View(list);
}
And in view
#{
var gd = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
gd.Pager(WebGridPagerModes.NextPrevious);}
#gd.GetHtml(tableStyle: "table",
columns: gd.Columns(
gd.Column("AuthorId", "AuthorId"),
gd.Column("Fname", " Fname"),
gd.Column("Lname", "Lname", style: "description")
))
Short answer
Directly answering your question:
var tableList = new List<RegresDB_TableName>();
int numRows = ds.Tables["RegresDB"].Rows.Count;
for (int i = 0; i < numRows; i++)
{
string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
tableList.Add(new RegresDB_TableName() { TableName = tblName };
}
return View(tableList);
Long answer (that's actually shorter)
Try out dapper-dot-net.
Your code could change to something like:
string sqlStr = "SELECT * FROM [RegressionResults].[dbo].[Diff_MasterList] ORDER BY TableName";
return sqlConn.Query<RegresDB_TableName>(sqlStr);
If you're stuck with using DAO, I would suggest not using a DataSet and instead use a strongly typed class with the speed of SqlDataReader.GetValues() method. It's more work, but it has to be done somewhere if you want strongly typed classes which I would highly recommend.
public class Person
{
public Person(Object[] values]
{
this.FirstName = (string)values[0];
this.LastName = (string)values[1];
this.Birthday = (DateTime)values[2];
this.HasFavoriteColor = (bool)values[3];
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
public DateTime Birthday { get; private set; }
public bool HasFavoriteColor { get; private set; }
}
public static void DbRegressionExec()
{
List<Person> viewModel = new List<Person>();
// SELECT TABLE CONTENTS FROM SQL !!
RegressDB_TableList regresDB = new RegressDB_TableList();
string sqlStr = "select
FirstName
,LastName
,Birthday
,HasFavoriteColor
from [RegressionResults].[dbo].[Diff_MasterList]
order by TableName";
// POPULATE VIEWMODEL OBJECT
sqlConn.Open();
try
{
using (SqlCommand com = new SqlCommand(sqlStr, sqlConn))
{
using (SqlDbReader reader = com.ExecuteReader())
{
while(reader.Read())
{
viewModel.Add(new Person(com.GetValues()));
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
sqlConn.Close();
}
return this.View(viewModel);
}
Controller code
//pQ is your query you have created
//P4DAL is the key name for connection string
DataSet ds = pQ.Execute(System.Configuration.ConfigurationManager.ConnectionStrings["Platform4"].ConnectionString);
//ds will be used below
//create your own view model according to what you want in your view
//VMData is my view model
var _buildList = new List<VMData>();
{
foreach (DataRow _row in ds.Tables[0].Rows)
{
_buildList.Add(new VMData
{
//chose what you want from the dataset results and assign it your view model fields
clientID = Convert.ToInt16(_row[1]),
ClientName = _row[3].ToString(),
clientPhone = _row[4].ToString(),
bcName = _row[8].ToString(),
cityName = _row[5].ToString(),
provName = _row[6].ToString(),
});
}
}
//you will use this in your view
ViewData["MyData"] = _buildList;
View
#if (ViewData["MyData"] != null)
{
var data = (List<VMData>)ViewData["MyData"];
<div class="table-responsive">
<table class="display table" id="Results">
<thead>
<tr>
<td>Name</td>
<td>Telephone</td>
<td>Category </td>
<td>City </td>
<td>Province </td>
</tr>
</thead>
<tbody>
#foreach (var item in data)
{
<tr>
<td>#Html.ActionLink(item.ClientName, "_Display", new { id = item.clientID }, new { target = "_blank" })</td>
<td>#item.clientPhone</td>
<td>#item.bcName</td>
<td>#item.cityName</td>
<td>#item.provName</td>
</tr>
}
</tbody>
</table>
</div>
}

Resources