I have been battling this for some time now without success. So Your help is extremely appreciated.
I have created a dropdown list from sql database. What I want to do is to set up an onchange selection event to take the value selected in the dropdown list and use it as a variable in my sql script to get the data from the database. My problem is not being able to get the selected item form the dropdown list to show in the Controller file and then add it to the sql script. I am new to Asp Core 6 and really struggling to understand the changes. Any and all help is appreciated
The View
Code
#model CISIII.Models.Dropdownlist
#*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*#
#{
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<h1>Customer Data Update</h1>
<form method="post" >
<hr/>
<table cellpadding="10" cellspacing="10">
<tr>
<td><strong>Customer Name</strong></td>
<td>
#Html.DropDownListFor(m => m.Cust1list, new SelectList(#Model.Cust1list, "Coname", "Coname"), "Select Company", htmlAttributes: new { #class = "form-control", id="coname"})
</td>
<td><input type="text" name="serviceName" value="" /></td>
</tr>
#{
if (Model.Cust2list != null)
{
foreach (var Cust in Model.Cust2list)
{
<tr>
<td><strong>Company Name</strong></td>
<td><td><input value="#Cust.Coname" id="coname" type="text"/></td>
</tr>
<tr>
<td><strong>First Name</strong></td>
<td><input value="#Cust.Fname" id="Fname" type="text"/></td>
<td><strong>Surname</strong></td>
<td><input value="#Cust.Sname" id="sname" type="text"/></td>
</tr>
<tr>
<td><strong>Tel</strong></td>
<td><input value="#Cust.Tel" id="tel" type="text"/></td>
<td><strong>Email</strong></td>
<td><input value="#Cust.Email" id="email" type="text"/></td>
</tr>
<tr>
<td><strong>Address</strong></td>
<td><input value="#Cust.Add1" id="add1" type="text"/></td>
<td><strong>Address</strong></td>
<td><input value="#Cust.Add2" id="add2" type="text"/></td>
</tr>
<tr>
<td><strong>Suburb</strong></td>
<td><input value="#Cust.Suburb" id="suburb" type="text"/></td>
<td><strong>State</strong></td>
<td><input value="#Cust.State" id="state" type="text"/></td>
</tr>
<tr>
<td><strong>Post Code</strong></td>
<td><input value="#Cust.Pcode" id="pcode" type="text"/></td>
<td><strong>Where did you find Us</strong></td>
<td><input value="#Cust.Findus" id="findus" type="text"/></td>
</tr>
<tr>
<td><strong>Product Category</strong></td>
<td><input value="#Cust.Prod_cat" id="prodcat" type="text"/></td>
<td><strong>Notes</strong></td>
<td><input value="#Cust.Question2" id="question2" type="text"/></td>
</tr>
<tr>
<td><strong>Industry</strong></td>
<td><input value="#Cust.Indlist" id="ddlindustry" type="text"/></td>
<td><strong>Status</strong></td>
<td><input value="#Cust.Statlist" id="status" type="text"/></td>
</tr>
<tr>
<td><strong>Start Date</strong></td>
<td><input value="#Cust.Start_date" id="start_date" type="text"/></td>
<td><strong>End Date</strong></td>
<td><input value="#Cust.End_date" id="end_date" type="text"/></td>
</tr>
}
}
}
<tr>
<td>
<button onclick="GetCust2List" value"Submit">Click me</button>
#* <input id="Submit" type="submit" value="submit" formaction="GetCust2List" />*#
</td>
</tr>
</table>
</form>
</body>
</html>
The Model
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Data.SqlClient;
namespace CISIII.Models
{
public class Dropdownlist
{
public DateTime? DtmDate { get; set; }
public List<Status_List> Statlist { get; set; }
public List<Product_List> Prodlist { get; set; }
public List<Industry_List> Indlist { get; set; }
public List<Findus_List> Findlist { get; set; }
public List<Customers_List> Cust1list { get; set; }
public List<NE_Cust_List> Cust2list { get; set; }
public IActionResult? GetDetails { get; set; }
public int SaveDetails { get; set; }
}
public class Status_List
{
public int Id { get; set; }
public string? Description { get; set; }
}
public class Product_List
{
public int Id { get; set; }
public string? prod_cat { get; set; }
}
public class Industry_List
{
public int Id { get; set; }
public string? Description { get; set; }
}
public class Findus_List
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class Customers_List
{
public int Id { get; set; }
public string? Fname { get; set; }
public string? Sname { get; set; }
public string? Coname { get; set; }
public string? Tel { get; set; }
public string? Email { get; set; }
public string? Add1 { get; set; }
public string? Add2 { get; set; }
public string? Suburb { get; set; }
public string? State { get; set; }
public string? Pcode { get; set; }
public string? Findus { get; set; }
public string? Prod_cat { get; set; }
public string? Question2 { get; set; }
public string? Indlist { get; set; }
public string? Statlist { get; set; }
public string? Start_date { get; set; }
public string? End_date { get; set; }
}
public class NE_Cust_List
{
public int Id { get; set; }
public string? Fname { get; set; }
public string? Sname { get; set; }
public string? Coname { get; set; }
public string? Tel { get; set; }
public string? Email { get; set; }
public string? Add1 { get; set; }
public string? Add2 { get; set; }
public string? Suburb { get; set; }
public string? State { get; set; }
public string? Pcode { get; set; }
public string? Findus { get; set; }
public string? Prod_cat { get; set; }
public string? Question2 { get; set; }
public string? Indlist { get; set; }
public string? Statlist { get; set; }
public string? Start_date { get; set; }
public string? End_date { get; set; }
}
public class UserDataModel
{
public string? Fname { get; set; }
public string? Sname { get; set; }
public string? Coname { get; set; }
public string? Tel { get; set; }
public string? Email { get; set; }
public string? Add1 { get; set; }
public string? Add2 { get; set; }
public string? Suburb { get; set; }
public string? State { get; set; }
public string? Pcode { get; set; }
public string? Findus { get; set; }
public string? Prod_cat { get; set; }
public string? Question2 { get; set; }
public string? Indlist { get; set; }
public string? Web { get; set; }
public string? Statlist { get; set; }
public string? Start_date { get; set; }
public string? End_date { get; set; }
public int SaveDetails()
{
SqlConnection con = new SqlConnection("Data Source=bhd-web2;User ID=sa;Password=Sabril01;Database=CAS; Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
string query = "INSERT INTO Customers (fname, sname, coname, tel, email, add1, add2, suburb, state, pcode, " +
"findus, prod_cat, question2, ddlindustry, web, status, start_date, end_date, entry_date) values ('" + Fname + "','" + Sname + "','" + Coname + "', " +
"'" + Tel + "','" + Email + "','" + Add1 + "','" + Add2 + "','" + Suburb + "','" + State + "','" + Pcode + "','" + Findus + "','" + Prod_cat + "', " +
"'" + Question2 + "','" + Indlist + "','" + Web + "','" + Statlist + "','" + Start_date + "','" + End_date + "', getdate())";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
}
The Controller
using Microsoft.AspNetCore.Mvc;
using CISIII.Models;
using System.Data.SqlClient;
using System.Data;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace CISIII.Controllers
{
public class HomeController : Controller
{
public IConfigurationRoot GetConnection()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appSettings.json").Build();
return builder;
}
Dropdownlist dropdownlist = new Dropdownlist();
public IActionResult Index()
{
return View();
}
public List<Status_List> GetStatusList()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select id, description From status order by description asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Status_List> status = new List<Status_List>();
if (idr.HasRows)
{
while (idr.Read())
{
status.Add(new Status_List
{
Id = Convert.ToInt32(idr["id"]),
Description = Convert.ToString(idr["description"]),
});
}
}
con.Close();
return status;
}
public List<Product_List> GetProdList()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select id, prod_cat_name From prod_cat order by prod_cat asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Product_List> products = new List<Product_List>();
if (idr.HasRows)
{
while (idr.Read())
{
products.Add(new Product_List
{
Id = Convert.ToInt32(idr["id"]),
prod_cat = Convert.ToString(idr["prod_cat_name"]),
});
}
}
con.Close();
return products;
}
public List<Industry_List> GetIndList()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select id, description From industry order by description asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Industry_List> industry = new List<Industry_List>();
if (idr.HasRows)
{
while (idr.Read())
{
industry.Add(new Industry_List
{
Id = Convert.ToInt32(idr["id"]),
Description = Convert.ToString(idr["description"]),
});
}
}
con.Close();
return industry;
}
public List<Findus_List> GetFindList()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select id, cat_name From findus order by cat_name asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Findus_List> find = new List<Findus_List>();
if (idr.HasRows)
{
while (idr.Read())
{
find.Add(new Findus_List
{
Id = Convert.ToInt32(idr["id"]),
Name = Convert.ToString(idr["cat_name"]),
});
}
}
con.Close();
return find;
}
public IActionResult View1()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult updatecust()
{
dropdownlist.Cust1list = GetCust1List();
return View(dropdownlist);
}
public IActionResult newcust()
{
Dropdownlist multi_Dropdownlist = new Dropdownlist
{
Statlist = GetStatusList(),
Prodlist = GetProdList(),
Indlist = GetIndList(),
Findlist = GetFindList(),
};
return View(multi_Dropdownlist);
}
[HttpPost]
public IActionResult GetDetails()
{
UserDataModel umodel = new UserDataModel();
umodel.Fname = HttpContext.Request.Form["fname"].ToString();
umodel.Sname = HttpContext.Request.Form["sname"].ToString();
umodel.Coname = HttpContext.Request.Form["coname"].ToString();
umodel.Tel = HttpContext.Request.Form["tel"].ToString();
umodel.Email = HttpContext.Request.Form["email"].ToString();
umodel.Add1 = HttpContext.Request.Form["street_number"].ToString();
umodel.Add2 = HttpContext.Request.Form["route"].ToString();
umodel.Suburb = HttpContext.Request.Form["locality"].ToString();
umodel.State = HttpContext.Request.Form["administrative_area_level_1"].ToString();
umodel.Pcode = HttpContext.Request.Form["postal_code"].ToString();
umodel.Findus = HttpContext.Request.Form["Findlist"].ToString();
umodel.Prod_cat = HttpContext.Request.Form["Prodlist"].ToString();
umodel.Question2 = HttpContext.Request.Form["question2"].ToString();
umodel.Indlist = HttpContext.Request.Form["Indlist"].ToString();
umodel.Web = HttpContext.Request.Form["web"].ToString();
umodel.Statlist = HttpContext.Request.Form["Statlist"].ToString();
umodel.Start_date = HttpContext.Request.Form["start_date"].ToString();
umodel.End_date = HttpContext.Request.Form["end_date"].ToString();
int result = umodel.SaveDetails();
return View("Index");
}
public List<Customers_List> GetCust1List()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select * From CA_Form order by coname asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Customers_List> cust1 = new List<Customers_List>();
IEnumerable<Customers_List> cust1a = cust1;
if (idr.HasRows)
{
while (idr.Read())
{
cust1.Add(new Customers_List
{
Id = Convert.ToInt32(idr["id"]),
Coname = Convert.ToString(idr["coname"]),
Fname = Convert.ToString(idr["fname"]),
Sname = Convert.ToString(idr["sname"]),
});
}
}
// System.Diagnostics.Debug.WriteLine(cust1.Count);
con.Close();
return cust1;
}
public List<NE_Cust_List> GetCust2List()
{
System.Diagnostics.Debug.WriteLine("Hello");
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select * From CA_Form where coname like '%Sims%'", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<NE_Cust_List> cust2 = new List<NE_Cust_List>();
IEnumerable<NE_Cust_List> cust2a = cust2;
if (idr.HasRows)
{
while (idr.Read())
{
cust2.Add(new NE_Cust_List
{
Id = Convert.ToInt32(idr["id"]),
Fname = Convert.ToString(idr["fname"]),
Sname = Convert.ToString(idr["sname"]),
Coname = Convert.ToString(idr["coname"]),
Tel = Convert.ToString(idr["tel"]),
Email = Convert.ToString(idr["email"]),
Add1 = Convert.ToString(idr["add1"]),
Add2 = Convert.ToString(idr["add2"]),
Suburb = Convert.ToString(idr["suburb"]),
State = Convert.ToString(idr["state"]),
Pcode = Convert.ToString(idr["pcode"]),
Findus = Convert.ToString(idr["findus"]),
Prod_cat = Convert.ToString(idr["prod_cat"]),
Question2 = Convert.ToString(idr["question2"]),
Indlist = Convert.ToString(idr["ddlindustry"]),
Statlist = Convert.ToString(idr["status"]),
Start_date = Convert.ToString(idr["start_date"]),
End_date = Convert.ToString(idr["end_date"]),
});
}
con.Close();
System.Diagnostics.Debug.WriteLine("hello 2");
System.Diagnostics.Debug.WriteLine(cust2.Count);
}
dropdownlist.Cust2list= cust2;
return cust2;
}
[HttpPost]
public ActionResult ShowAllMobileDetails(Dropdownlist dl1 , FormCollection form)
{
string conameValue = form["coname"].ToString();
System.Diagnostics.Debug.WriteLine(conameValue);
return View(dl1);
}
}
}
In Asp.Net Core, We can use SelectListItem to pass data from controller to DropDownList in page, Because there are so many properties in your model, It's very complicated to use them write a demo, So i write a simple demo here set up a onchange selection event to dropdownlist.
//write a simple model and hard code here
List<Student> students = new List<Student>
{
new Student{
Id = "0",
Name = "AAA"
},
new Student
{
Id = "1",
Name = "BBB"
},
new Student
{
Id = "2",
Name = "CCC"
},
new Student
{
Id = "3",
Name ="DDD"
}
};
public IActionResult Index()
{
List<SelectListItem> test = new List<SelectListItem>();
foreach(var student in students)
{
//add value to dropdownlist
test.Add(new SelectListItem { Text = student.Name, Value = student.Id });
}
ViewBag.list = test;
return View();
}
View
<select asp-items="ViewBag.list" onchange="change(this.value)"></select>
#*set an onchange event to get the value of dropdownlist and send it to the specified action*#
#section Scripts
{
<script>
function change(value){
var Id = {
'Id':value
};
$.ajax({
type: "Post",
url: "/Home/GetId",
data: Id,
})
}
</script>
}
Then after you select an option, you can get the It's value in Home/GetId and then add it to the sql script.
I've created a CSV parser using the most recommended nuget I could find on here, CSVReader. I think my code is almost there its just posting the file to the controller actionmethod I can't quite find enough on. I get the error:
System.IO.FileNotFoundException: 'Could not find file 'C:\Program Files (x86)\IIS Express\System.Web.HttpPostedFileWrapper'.'
Controller action method:
[HttpPost]
public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
{
if (ModelState.IsValid)
{
using (CsvReader csv = new CsvReader(new StreamReader(attachmentcsv.ToString()), true))
{
csv.Configuration.HasHeaderRecord = true;
var records = csv.GetRecords<Client>().ToList();
foreach (var item in records)
{
String Strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "").Replace("https://", "").Replace("http://", "").Replace("www.", "");
string[] URLtests = { "https://www." + Strip, "http://www." + Strip, "https://" + Strip, "http://" + Strip };
string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
var newclient = new Client { clientN = item.clientN, homePage = Metric[0], clientEmail = item.clientEmail, contName = item.contName.First().ToString().ToUpper() + item.contName.Substring(1), monthlyQuota = item.monthlyQuota, TrustFlow = Int32.Parse(Metric[1]), CitationFlow = Int32.Parse(Metric[2]), RI = Int32.Parse(Metric[3]), MJTopicsID = item.MJTopicsID, UserTableID = UserTableID };
ViewBag.newdomain = newclient;
db.Clients.Add(newclient);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
return RedirectToAction("Index");
View upload button:
#using (Html.BeginForm("CreateBulk", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="attachment">Select a Csv File</label>
<label class="btn btn-default btn-file">
<input type="file" name="attachmentcsv" id="attachmentcsv" hidden>
</label>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
}
Client Model:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Linkofy.Models
{
public class Client
{
public int ID { get; set; }
[Required]
[Display(Name = "Client")]
public string clientN { get; set; }
[Display(Name = "Website")]
public string homePage{ get; set; }
[EmailAddress]
[Display(Name = "Contact Email")]
public string clientEmail { get; set; }
[Display(Name = "Contact Name")]
public string contName { get; set; }
[Display(Name = "Monthly")]
public int monthlyQuota { get; set; }
[Display(Name = "TF")]
public int TrustFlow { get; set; }
[Display(Name = "CF")]
public int CitationFlow { get; set; }
[Display(Name = "RIPs")]
public int RI { get; set; }
public int? MJTopicsID { get; set; }
public virtual MJTopics MJTopics { get; set; }
public int UserTableID { get; set; }
public virtual UserTable UserTable { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual ICollection<Status> Statuss { get; set; }
}
}
You should check out: File upload in MVC
But looking into your code there are a few things that I wanted to point out:
Isolating the attachmentcsv.ToString() line it appears that this returns the type of System.Web.HttpPostedFileWrapper, this is why this string is being appended onto the file location.
I believe you may be looking for the attachmentcsv.FileName, which according to documentation of the type (https://msdn.microsoft.com/en-us/library/system.web.httppostedfilewrapper(v=vs.110).aspx)
Gets the fully qualified name of the file on the client
I'm not sure if you are using the framework or the core version of ASP, but I believe in the framework version of ASP the "correct" way of accessing upload files (as indicated in the linked answer) is to go through the Request object:
Request.Files.
https://msdn.microsoft.com/en-us/library/system.web.httprequest.files(v=vs.110).aspx
In the core version of ASP you can have a IFileForm as indicated here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
Hope this helps
I have looked into this problem on other questions on Stackoverflow but none that I have found seem to be the right version of the problem for this code.
I thought that it might be because the list in the model is the same as the one in the controller.
Here is my Controller code:
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
//TODO:Lägga till varje column så att dom kan flyttas till vyn innan dom flyttas till denna innläggning i databasen.
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [Sheet 1$]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string FileLocation = Server.MapPath("~/Content/") + Request.Files["FileUpload"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(FileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
ds.ReadXml(xmlreader);
xmlreader.Close();
}
o.DCResults = new List<string>();
for (int y = 0; y < ds.Columns.Count; y++)
{
string dc = ds.Columns[y].ColumnName.ToString();
o.DCResults.Add(dc.ToString());
}
DataSet exceldata = new DataSet();
exceldata.Tables.Add(ds);
}
}
//TODO: Errormessage here:
return View();
}
And this is my view (where the error occurs when I try to make a dropdownlist with the list result from the DCResults list so that users can map each of the results to a column name that I get from the same model that I use for the list.):
#model BFProj2.Models.OurColumns
#{
ViewBag.Title = "Import";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Import</h2>
Firstname:
<body>
#Html.DisplayNameFor(modelItem => modelItem.FirstName)
#Html.EditorFor(modelItem => modelItem.FirstName)
<div class="display-field">
#Html.DropDownList("DCResults",(IEnumerable<SelectListItem>)ViewBag.DCResults)
</div>
</body>
And here is my model where I get the list and the new column names:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq;
using System.ComponentModel;
namespace BFProj2.Models
{
public class OurColumns
{
public Guid ID { get; set; }
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Email")]
public string Email { get; set; }
[DisplayName("Comment")]
public string Comment { get; set; }
[DisplayName("Username")]
public string UserName { get; set; }
[DisplayName("Firstname")]
public string FirstName { get; set; }
[DisplayName("Lastname")]
public string LastName { get; set; }
[DisplayName("Last activity date")]
public DateTime? LastUpdateDate { get; set; }
[DisplayName("Title")]
public string Title { get; set; }
[DisplayName("Abstract number")]
public int AbstrNum { get; set; }
[DisplayName("Poster title")]
public string PosterTitle { get; set; }
[DisplayName("Workshop")]
public string Workshop { get; set; }
[DisplayName("Keywords")]
public string Keywords { get; set; }
[DisplayName("Institution")]
public string Institution { get; set; }
[DisplayName("Collaboration email")]
public string CollabEmail { get; set; }
[DisplayName("DCResults")]
public List<string> DCResults { get; set; }
}
}
Based on your comments, firstly you need a property in your model to bind the selected value to
public string DCResults { get; set; } // this will have the selected value
Assuming your controller generates a list of columns names (for example)
List<string> columns = new List<string>() { "Column 1", "Column 2", "Column 3" });
then you need to create a SelectList and assign it a ViewBag property
ViewBag.DCResultsList = new SelectList(columns); // note should not be the same name as the model property
Then in the view
#Html.DropDownListFor(m => m.DCResults, (SelectList)ViewBag.DCResultsList)
Note the are other overloads for creating a SelectList and for DropDownListFor
I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public float Rating { get; set; }
public string Industry { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string CountryCode { get; set; }
public virtual Snapshot Snapshot { get; set; }
}
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public DateTime DateTimeSent { get; set; }
public string Subject { get; set; }
public string Html { get; set; }
public string Image { get; set; }
public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
{
public Brand Brand { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
controller:
public ActionResult Index(string brandGuid)
{
BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
Brand brand = GetBrand(brandGuid);
viewModel.Brand = brand;
List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
viewModel.SnapshotItems = snapshot;
List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList.AsEnumerable());
}
private Brand GetBrand(string brandGuid)
{
Brand brand = new Brand();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
if (dbResult.Read())
{
brand.Guid = dbResult["brand_guid"].ToString();
brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
brand.Industry = dbResult["industry_name"].ToString();
}
dbResult.Close();
dbConn.Close();
return brand;
}
private List<Snapshot> GetBrandSnapshots(int brandId)
{
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
List<Snapshot> snapshots = new List<Snapshot>();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Subject = dbResult["subject"].ToString(),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Email = dbResult["email"].ToString(),
ContentType = dbResult["content_type"].ToString(),
Type = dbResult["type"].ToString()
});
}
dbResult.Close();
dbConn.Close();
return snapshots;
}
edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
#model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#item.Brand.Guid;
for(int i = 0; i< #item.SnapshotItems.Count; i++)
{
#item.SnapshotItems[i].Subject<br/>
}
}
That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.
you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
while (dbResult.Read())
{
BrandEmailList brandSnapshots = new BrandEmailList (); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
while (dbResult.Read())
{
Snapshot brandSnapshots = new Snapshot(); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
// ...
}
public class BrandEmailList : List<Snapshot>
{
}
You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
var brand = GetBrand(brandName);
var brandSnapshots = GetBrandSnapshots();
return View(brand, brandSnapshots);
}
private Brand GetBrand(string brandName)
{
try
{
var brand = new Brand();
brand.Name = brandName;
// database stuffs ...
return brand;
}
catch (Exception ex)
{
throw ex;
}
}
private List<Snapshot> GetBrandSnapshots()
{
// ...
// DB stuffs -- that *really* should not be in the controller anyways.
// ...
var snapshots = new List<BrandEmailList>();
while (dbResult.Read())
{
// object initializer syntax
snapshots.Add(new Snapshot {
ID = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString(),
DateTimeSent = dbResult["date_sent"],
Subject = dbResult["subject"].ToString(),
Image = dbResult["image"],
});
}
return snapshots
}
As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.
I am having trouble with the representation of a date in JSON. I am using Service Stack as a web service to get the data from. My code on the server side is as follows:
public object Execute(GetNoPatientList request)
{
NoPatientList _noPatientList = new NoPatientList();
List<string> _noMatchPatientList = new List<string>();
List<NoPatientList> _newList = new List<NoPatientList>();
try
{
using (SqlConnection cn = new SqlConnection(Database.WaldenWebConnection))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandText = "select [DateTimeStamp] as DateCreated,[ID],[PatientMRN],[FirstName],[MiddleName]"
+ " ,[LastName],convert(varchar,[DOB],101) as DOB,[Sex],[Note],[Source] as Interface"
+ " from PatientNoMatch"
+ " where FoundMatch = 'F'"
+ " and Show = 'T'"
+ " order by DateTimeStamp desc";
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NoPatientList _noPatientList1 = new NoPatientList();
_noPatientList1.PatientMRN = dr["PatientMRN"].ToString();
_noPatientList1.FirstName = dr["FirstName"].ToString();
_noPatientList1.MiddleName = dr["MiddleName"].ToString();
_noPatientList1.LastName = dr["LastName"].ToString();
_noPatientList1.DOB = dr["DOB"].ToString();
_noPatientList1.Sex = dr["Sex"].ToString();
_noPatientList1.Note = dr["Note"].ToString();
_noPatientList1.DateCreated = dr.GetDateTime(0);
_noPatientList1.Interface = dr["Interface"].ToString();
_newList.Add(_noPatientList1);
}
return _newList;
}
}
}
catch
{
return _newList;
}
}
The type is represented as follows:
[DataContract]
public class NoPatientList
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string PatientMRN { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Sex { get; set; }
[DataMember]
public string DOB { get; set; }
[DataMember]
public string Note { get; set; }
[DataMember]
public DateTime DateCreated { get; set; }
[DataMember]
public string Interface { get; set; }
}
The web service is being consumed by a Silverlight application from the following call:
/InterfaceUtility/servicestack/json/syncreply/
The Silverlight application is processing the code into a grid using the following code
private void GetNoPatientMatchData()
{
try
{
gridViewNoMatch.ItemsSource = null;
}
catch { }
_client = new WebClient();
_client.OpenReadCompleted += (a, f) =>
{
if (!f.Cancelled && f.Error == null)
{
_listOfNoPatientsMatches = new List<NoPatientList>();
MemoryStream _memoryStream = new MemoryStream();
f.Result.CopyTo(_memoryStream);
_memoryStream.Position = 0;
StreamReader _streamReader = new StreamReader(_memoryStream);
string _memoryStreamToText = _streamReader.ReadToEnd();
List<NoPatientList> _deserializedNoPatientList = (List<NoPatientList>)Newtonsoft.Json.JsonConvert.DeserializeObject(_memoryStreamToText, typeof(List<NoPatientList>));
gridViewNoMatch.ItemsSource = _deserializedNoPatientList;
}
else
{
MessageBox.Show(f.Error.Message,
"Error", MessageBoxButton.OK);
}
};
_client.OpenReadAsync(new Uri(_serviceUri + "getnopatientlist"));
The issue is that the times on DateTime field appear to always 6 hours off.
Any ideas as to what is going on?
This is probably a time zone issue. Check that:
Your webservice is returning you dates/times in UTC format.
Your code is parsing these dates/times as UTC dates and times.