I cannot find how to create the constructor and find the solution - spring-mvc

java.lang.IllegalStateException: No primary or single unique constructor found for class java.lang.Long
2023-01-28 18:19:08.735 ERROR 7152 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or single unique constructor found for class java.lang.Long] with root cause
package com.example.prescription.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.*;
#SuppressWarnings("ALL")
#Entity
#Table(name="drugs")
public class Drug implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name="name")
private String drugName;
#Column(name="description")
private String description;
#Column(name = "dosage")
private String dosage;
#Column(name = "side_effects")
private String side_effects;
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#ManyToMany(mappedBy = "drugs",cascade = CascadeType.ALL)
private Set<Patient> patients = new HashSet<>();
public Drug() {
}
public Drug(String drugName) {
this.drugName = drugName;
}
public Drug(Long id, String drugName, String description, String dosage, String side_effects, Date createdAt) {
this.id = id;
this.drugName = drugName;
this.description = description;
this.dosage = dosage;
this.side_effects = side_effects;
this.createdAt = createdAt;
}
public Drug(Patient patient, Drug drug, Date date) {
}
//GETTERS SETTERS
}
package com.example.prescription.model;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
#Entity
#Table(name = "patients")
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "dob")
private String dateOfBirth;
#NotEmpty(message = "Phone number may not be empty")
#Size(min = 10, max = 10)
#Column(name = "phone")
private String phone;
#NotEmpty(message = "Email may not be empty")
#Size(min = 7, max = 50)
#Column(name = "email")
private String email;
#Column(name = "fathers_name")
private String fathersName;
#Column(name = "mothers_name")
private String mothersName;
#Column(name = "amka")
#Size(min = 11, max = 11)
#Pattern(regexp = "^[0-9]+$", message = "AMKA must contain only numbers")
private String amka;
#Column(name = "id_card")
#Pattern(regexp = "^[a-zA-Z0-9]+$", message = "ID must contain only letters and numbers")
private String idCard;
#Column(name = "city")
private String city;
#Column(name = "postal_code")
#Size(min = 5, max = 5)
#Pattern(regexp = "^[0-9]+$", message = "PC must contain only numbers")
private String postalCode;
#Column(name = "symptoms")
private String symptoms;
#Column(name = "pharmacy")
private String pharmacy;
#Column(name = "doctor_name")
private String doctorsName;
#Column(name = "message")
private String message;
#ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
#JoinTable(name = "patient_drug",joinColumns = #JoinColumn(name = "patient_id"),
inverseJoinColumns = #JoinColumn(name = "drug_id"))
private Set<Drug> drugs;
public Patient(Patient patient, Drug drug, Date date) {
}
public Patient() {
}
GETTERS SETTERS
public void addDrug(Drug drug){
this.drugs.add(drug);
drug.getPatients().add(this);
}
public void removeDrug(Drug drug) {
this.drugs.remove(drug);
drug.getPatients().remove(this);
}
public void removeDrugs() {
Iterator<Drug> iterator = this.drugs.iterator();
while (iterator.hasNext()) {
Drug drug = iterator.next();
drug.getPatients().remove(this);
iterator.remove();
}
}
}
package com.example.prescription.controller;
import com.example.prescription.model.Drug;
import com.example.prescription.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.example.prescription.service.DrugService;
import com.example.prescription.service.PatientService;
import javax.activation.MimeType;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
#Controller
public class PatientController {
private final PatientService patientService;
private final DrugService drugService;
public PatientController(#Autowired PatientService patientService,
#Autowired DrugService drugService) {
this.patientService = patientService;
this.drugService = drugService;
}
}
#GetMapping("/prescribeDrugs/{id}")
public ModelAndView prescribeDrugs(#PathVariable("id") String id) {
Long pid = Long.parseLong(id);
ModelAndView mav = new ModelAndView("patientFormEdit");
Patient formPatient = patientService.findPatientById(pid);
mav.addObject("patient", formPatient);
mav.addObject("drugs", drugService.getAllDrugs());
return mav;
}
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
Map<String,String> drug = new LinkedHashMap<String,String>();
drug .put("DP", "DEPON");
drug .put("AS", "ASPIRIN");
drug .put("PN", "PANADOL");
referenceData.put("drugList", drug );
return referenceData;
}
#PostMapping("/prescribeDrugs/Patient/{id}")
public String prescribePatientDrugs(#Valid Patient patient, String id, #ModelAttribute(value = "drugs") Long drugId, BindingResult result, MimeType request) {
if (result.hasErrors()) {
return "patients";
}
try {
Long pId = Long.parseLong(request.getParameter("pId"));
Patient formPatient = patientService.findPatientById(pId);
Drug drug = drugService.findById(drugId);
formPatient.setCity(patient.getCity());
formPatient.setEmail(patient.getEmail());
formPatient.setPhone(patient.getPhone());
formPatient.setSymptoms(patient.getSymptoms());
formPatient.setPharmacy(patient.getPharmacy());
formPatient.setDoctorsName(patient.getDoctorsName());
formPatient.setMessage(patient.getMessage());
Drug patientDrug = new Drug(patient, drug, new Date());
drugService.save(drug);
formPatient.getDrugs().add(patientDrug);
patientService.updatePatient(formPatient);
} catch (NumberFormatException n) {
System.out.println("error");
}
return "redirect:/allPatients";
}
}
<form th:action="#{/prescribeDrugs/Patient/{id}(id = ${patient.id})}" method="post" th:object="${patient}">
<div class="container prescription-form">
<div class="row">
<div class="col-lg-12 col-12">
<form>
<h1>Electronic Prescription Form</h1>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>Patient Name</span><input type="text" th:value="${patient.firstName}"
th:name="firstName" disabled/>
</label>
</div>
<span class="error_message">This field is required</span>
</div>
<form:select path="drug" items="${drugList}" />
<select id="drug" name="drug">
<option value="AS">ASPIRIN</option>
<option value="DE">DEPON</option>
<option value="PN">PANADOL</option>
</select>

Related

Picocli: arbitrary length of paired parameters

In Picocli, is it possible to pair parameters of an arbitrary length? For example:
grades Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0
where each pair must have a name and a grade but the total length is unknown, i.e.:
grades <name> <grade> [<name> <grade>]*
A parameter map is the closest that appears might work, e.g.
#Parameters(index = "0..*") Map<String, float> grades;
would parse:
grades Abby=4.0 Billy=3.5 Caily=3.5 Danny=4.0
into the map but it'd be nicer if the equals wasn't there...
Update: picocli 4.3 has been released with improved support for positional parameters in argument groups.
#Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
public class Grades implements Runnable {
static class StudentGrade {
#Parameters(index = "0") String name;
#Parameters(index = "1") BigDecimal grade;
}
#ArgGroup(exclusive = false, multiplicity = "1..*")
List<StudentGrade> gradeList;
#Override
public void run() {
gradeList.forEach(e -> System.out.println(e.name + ": " + e.grade));
}
public static void main(String[] args) {
System.exit(new CommandLine(new Grades()).execute(args));
}
}
Running the above program with this input:
Alice 3.5 Betty 4.0 "X Æ A-12" 3.5 Zaphod 3.4
Produces the following output:
Alice: 3.5
Betty: 4.0
X Æ A-12: 3.5
Zaphod: 3.4
Prior to picocli 4.3, applications can do the following to accomplish this:
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
#Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
public class Grades implements Runnable {
#Parameters(arity = "2",
description = "Each pair must have a name and a grade.",
paramLabel = "(NAME GRADE)...", hideParamSyntax = true)
List<String> gradeList;
#Override
public void run() {
System.out.println(gradeList);
Map<String, BigDecimal> map = new LinkedHashMap<>();
for (int i = 0; i < gradeList.size(); i += 2) {
map.put(gradeList.get(i), new BigDecimal(gradeList.get(i + 1)));
}
}
public static void main(String[] args) {
int exitCode = new CommandLine(new Grades()).execute(args);
System.exit(exitCode);
}
}

Joining two a ViewModel

This is the model:
public class ProCar
{
public string ProductName { get; set; }
public int ProductYear { get; set; }
public string CarBrand { get; set; }
public int CarEngine { get; set; }
}
I'm using this LINQ. How to save to a List of ProCar.
List<Product> p1 = db.Products.ToList();
List<Car> c1 = db.Cars.ToList();
List<ProCar> query = from pList in p1
join cList in c1 on pList equals cList.ProductId
select new { ProductName = pList.ProductName, ProductYear = pList.ProductYear, CarBrand = cList.CarBrand, CarEngine = cList.CarEngine };
return View();
Cannot find the issue.
Assuming you have relation between Product and Car :
var query = from product in db.Products
join car in db.Cars on product.Id equals car.ProductId//The relation between car and product
select new ProCar
{
ProductName = product.ProductName,
ProductYear = product.ProductYear,
CarBrand = car.CarBrand,
CarEngine = car.CarEngine
};
List<ProCar> proCarList = query.ToList();
See Join Clause
You are creating an anonymous list type that is unable to find/cast List type of ProCar. So you need to specify for tightly couply model binding as below
List<ProCar> query = ( from pList in p1
join cList in c1 on pList equals cList.ProductId
select new ProCar
{
ProductName = product.ProductName,
ProductYear = product.ProductYear,
CarBrand = car.CarBrand,
CarEngine = car.CarEngine
}).ToList();

Android Studio search existing sqlite db

So im developing an app and I want the user to search for a food item in my database and then to be returned with a list view of all food names that match the search criteria. I already have my slqite database created and added to the assets folder. The database is called foodDatabase.db
I have created the Database Helper like so:
package com.example.codebind.databasedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by tom on 15/03/2018.
*/
public class FoodDatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "FoodDatabase.db";
public static final String TABLE_NAME = "dataset";
public static final String COL_1 = "ID";
public static final String COL_2 = "Food";
public static final String COL_3 = "Description";
public static final String COL_4 = "Protein";
public static final String COL_5 = "Fat";
public static final String COL_6 = "Carbohydrate";
public static final String COL_7 = "Energy";
public static final String COL_8 = "Starch";
public static final String COL_9 = "Sugar";
public static final String COL_10 = "Cholesterol";
public FoodDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME +" (ID INTEGER
PRIMARY KEY AUTOINCREMENT,FOOD TEXT,DESCRIPTION TEXT,PROTEIN BLOB,FAT
BLOB,CARBOHYDRATE BLOB,ENERGY BLOB,STARCH BLOB,SUGAR BLOB,CHOLESTEROL BLOB)
");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
and currently my MainActivity.java is clean. I haven't touched it yet.
I'm asking for guidance on how to add a listener so that when the user enters a food name the app will return all foods from the foodDatabase.db that meets the search query.
Thanks
The basis of your search will be a query based upon the FOOD column (I believe).
e.g. SELECT * FROM dataset WHERE FOOD LIKE '%your_food%'
For example assume that your database has data such as (note only food and id columns have been populated with data) :-
Then the query SELECT * FROM dataset WHERE FOOD LIKE '%mash%' would result in :-
i.e. Foods with an id of 2 and 3 contain the food mash
You could run this query using the SQLiteDatabase query method. The query method returns a Cursor with the extracted data. So a method in your DatabaseHelper could be :-
public Cursor getFoodsWithProvidedFood(String provided_food) {
return this.getWritableDatabase().query(
TABLE_NAME,
null,
COL_2 + " LIKE '%" + provided_food + "%' ",
null,
null,
null,
null
);
}
Converting this into a complete but very basic App you could have :-
The Database Helper - FoodDatabaseHelper.java
public class FoodDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "FoodDatabase.db";
public static final String TABLE_NAME = "dataset";
public static final String COL_1 = "ID";
public static final String COL_2 = "Food";
public static final String COL_3 = "Description";
public static final String COL_4 = "Protein";
public static final String COL_5 = "Fat";
public static final String COL_6 = "Carbohydrate";
public static final String COL_7 = "Energy";
public static final String COL_8 = "Starch";
public static final String COL_9 = "Sugar";
public static final String COL_10 = "Cholesterol";
SQLiteDatabase sqLiteDatabase; //<<<< Added
public FoodDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
sqLiteDatabase = this.getWritableDatabase(); //<<<< Amended
}
//#Override
public void onNotRecommendedCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME +
" (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"FOOD TEXT," +
"DESCRIPTION TEXT," +
"PROTEIN BLOB," +
"FAT BLOB," +
"CARBOHYDRATE BLOB," +
"ENERGY BLOB," +
"STARCH BLOB," +
"SUGAR BLOB," +
"CHOLESTEROL BLOB)");
}
#Override
public void onCreate(SQLiteDatabase db) {
String crtsql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" +
COL_1 + " INTEGER PRIMARY KEY, " +
COL_2 + " TEXT, " +
COL_3 + " TEXT, " +
COL_4 + " BLOB, " +
COL_5 + " BLOB, " +
COL_6 + " BLOB, " +
COL_7 + " BLOB, " +
COL_8 + " BLOB, " +
COL_9 + " BLOB, " +
COL_10 + " BLOB " +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void insertFood(
String food,
String description,
byte[] protien,
byte[] fat,
byte[] carbohydrate,
byte[] energy,
byte[] starch,
byte[] sugar,
byte[] cholesterol) {
ContentValues cv = new ContentValues();
cv.put(COL_2,food);
cv.put(COL_3,description);
cv.put(COL_4,protien);
cv.put(COL_5,fat);
cv.put(COL_6,carbohydrate);
cv.put(COL_7,energy);
cv.put(COL_8,starch);
cv.put(COL_9,sugar);
cv.put(COL_10,cholesterol);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME,null,cv);
}
public Cursor getFoodsWithProvidedFood(String provided_food) {
return this.getWritableDatabase().query(
TABLE_NAME,
null,
COL_2 + " LIKE '%" + provided_food + "%' ",
null,
null,
null,
null
);
}
}
Notes
It will likely cause fewer issue if you have just one place where you define table and column names.
hence the changed onCreate
although column names in SQLite are case-insensitive the Cursor's getColumnIndex method (as used in the main activity) is case-sensitive (IMO a bug).
AUTOINCREMENT doesn't do what it implies, rather INTEGER PRIMARY KEY itself makes a column one that increments adding AUTOINCREMENT is a special case that ensures that the id is greater at the expense of overheads. Hence AUTOINCREMENT has been removed.
Two additional methods have been added
insertFood to insert(add) data to the dataset table.
getFoodsWithProvidedFood as described above.
The Activity - MainActivity.java
public class MainActivity extends AppCompatActivity {
FoodDatabaseHelper foodDBHlpr;
Cursor mCsr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
foodDBHlpr = new FoodDatabaseHelper(this);
byte[] dummy = new byte[]{0,1,2,3,4,5,6,7,8,9};
// Add some data oif none exists
if (DatabaseUtils.queryNumEntries(foodDBHlpr.getWritableDatabase(),FoodDatabaseHelper.TABLE_NAME) < 1) {
foodDBHlpr.insertFood("Fish and Chips", "The English Seaside meal",
dummy, dummy, dummy, dummy, dummy, dummy, dummy);
foodDBHlpr.insertFood("Bangers and Mash", "Yummy!!",
dummy, dummy, dummy, dummy, dummy, dummy, dummy);
foodDBHlpr.insertFood("Mashed Potatoe", "Boring",
dummy, dummy, dummy, dummy, dummy, dummy, dummy);
}
// get a Cursor with the extracted foods
mCsr = foodDBHlpr.getFoodsWithProvidedFood("Mash");
// Loop Through the Cursor
while (mCsr.moveToNext()) {
Log.d("FOODFOUND","You found the food called - " + mCsr.getString(mCsr.getColumnIndex(FoodDatabaseHelper.COL_2)));
}
if (mCsr.getCount() < 1) {
Log.d("FOODFOUND","No foods found that match the search criteria.");
}
mCsr.close(); //<<<< Should always close Cursors when done with them
}
}
Result in the Log :-
03-15 21:48:21.170 1702-1702/foodsdb.so49307874_foodsdb D/FOODFOUND: You found the food called - Bangers and Mash
03-15 21:48:21.170 1702-1702/foodsdb.so49307874_foodsdb D/FOODFOUND: You found the food called - Mashed Potatoe

To retrieve the value from session and assign it to a variable

In the below code i get all the ids in a arraylist and store it in a session in sample.aspx and retrieve the session value in test.aspx.Now i want to assign the project id to DataSet dsField in page load .How can i get that value separately.
sample.aspx
Button btnView = (Button)e.CommandSource;
Label lblProjectId = (Label)btnView.Parent.FindControl("ProjectID");
Label lblBatchID = (Label)btnView.Parent.FindControl("BatchID");
Label lblImageID = (Label)btnView.Parent.FindControl("ImageID");
Label lblReasons = (Label)btnView.Parent.FindControl("Reasons");
Label lblLayerID = (Label)btnView.Parent.FindControl("LayerID");
Label lblStatusID = (Label)btnView.Parent.FindControl("StatusID");
Label lblProcessID = (Label)btnView.Parent.FindControl("ProcessID");
ArrayList SearchUrlValues = new ArrayList();
SearchUrlValues.Add(lblProjectId);
SearchUrlValues.Add(lblBatchID);
SearchUrlValues.Add(lblProjectId);
SearchUrlValues.Add(lblImageID);
SearchUrlValues.Add(lblReasons);
SearchUrlValues.Add(lblLayerID);
SearchUrlValues.Add(lblStatusID);
SearchUrlValues.Add(lblProcessID);
Session["ProjectDetails"] = SearchUrlValues.ToArray();
Response.Write(SearchUrlValues);
test.aspx:
Array SearchUrlValues = (Array)Session["ProjectDetails"];
if (!IsPostBack)
{
DataSet dsField = GetFieldData(10);//how to assign projectid instead of 10
gmasFieldsContr.dtFieldsInfo = dsField.Tables[0];
gmasFieldsContr.EnumTable = dsField.Tables[1];
gmasFieldsContr.RegularExpressionTable = dsField.Tables[3];
gmasFieldsContr.BindData();
}
public DataSet GetFieldData(int iProjectID)
{
try
{
SqlParameter[] SqlParam = new SqlParameter[1];
SqlParam[0] = new SqlParameter("#i_ProjectID", SqlDbType.Int);
SqlParam[0].Value = iProjectID;
return ExecuteQuery(SqlParam, "spGetFieldData");
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
Edited
In Sample.aspx don't store SearchUrlValues as Array
Button btnView = (Button)e.CommandSource;
Label lblProjectId = (Label)btnView.Parent.FindControl("ProjectID");
Label lblBatchID = (Label)btnView.Parent.FindControl("BatchID");
Label lblImageID = (Label)btnView.Parent.FindControl("ImageID");
Label lblReasons = (Label)btnView.Parent.FindControl("Reasons");
Label lblLayerID = (Label)btnView.Parent.FindControl("LayerID");
Label lblStatusID = (Label)btnView.Parent.FindControl("StatusID");
Label lblProcessID = (Label)btnView.Parent.FindControl("ProcessID");
ArrayList SearchUrlValues = new ArrayList();
SearchUrlValues.Add(lblProjectId);
SearchUrlValues.Add(lblBatchID);
SearchUrlValues.Add(lblProjectId);
SearchUrlValues.Add(lblImageID);
SearchUrlValues.Add(lblReasons);
SearchUrlValues.Add(lblLayerID);
SearchUrlValues.Add(lblStatusID);
SearchUrlValues.Add(lblProcessID);
Session["ProjectDetails"] = SearchUrlValues; // Store it as ArrayList
Response.Write(SearchUrlValues);
Then test.aspx, convert Session object to ArrayList;
var SearchUrlValues = (ArrayList)Session["ProjectDetails"];
if (!IsPostBack)
{
var projectId = int.Parse(SearchUrlValues[0].ToString());
DataSet dsField = GetFieldData(projectId);//how to assign projectid instead of 10
gmasFieldsContr.dtFieldsInfo = dsField.Tables[0];
gmasFieldsContr.EnumTable = dsField.Tables[1];
gmasFieldsContr.RegularExpressionTable = dsField.Tables[3];
gmasFieldsContr.BindData();
}
By the way, please note that you're adding lblProjectId twice;
SearchUrlValues.Add(lblProjectId); // First
SearchUrlValues.Add(lblBatchID);
SearchUrlValues.Add(lblProjectId); // Second
Additionally, I would prefer to use an object to store these values in the session.
public class SearchUrlValues
{
public int lblProjectId { get; set; }
public int lblBatchID { get; set; }
public int lblImageID { get; set; }
public int lblReasons { get; set; }
public int lblLayerID { get; set; }
public int lblStatusID { get; set; }
public int lblProcessID { get; set; }
}
Then, instead of arraylist;
var newSearchUrlValues = new SearchUrlValues()
{
lblProjectId = lblProjectId,
lblBatchID = lblBatchID,
lblImageID = lblImageID,
lblReasons = lblReasons,
lblLayerID = lblLayerID,
lblStatusID = lblStatusID,
lblProcessID = lblProcessID
};
Session["ProjectDetails"] = newSearchUrlValues;
And retrieve it like;
var searchUrlValues = (SearchUrlValues)Session["ProjectDetails"];
var projectId = searchUrlValues.lblProjectId;
Try Like This
ArrayList SearchUrlValues = (ArrayList)Session["ProjectDetails"];
if (!IsPostBack)
{
DataSet dsField = GetFieldData(Convert.ToInt32(SearchUrlValues[0].ToString()));
//fetech 1st element of array List
gmasFieldsContr.dtFieldsInfo = dsField.Tables[0];
gmasFieldsContr.EnumTable = dsField.Tables[1];
gmasFieldsContr.RegularExpressionTable = dsField.Tables[3];
gmasFieldsContr.BindData();
}
public DataSet GetFieldData(int iProjectID)
{
try
{
SqlParameter[] SqlParam = new SqlParameter[1];
SqlParam[0] = new SqlParameter("#i_ProjectID", SqlDbType.Int);
SqlParam[0].Value = iProjectID;
return ExecuteQuery(SqlParam, "spGetFieldData");
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}

Having trouble with display colums from 4 tables MVC 3

I have a model as below and want to display items from 4 different table.
public class AuctionViewer
{
public int AuctionId { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
public DateTime startTime { get; set; }
public DateTime EndTime { get; set; }
public string Category { get; set; }
public int ExpectedHit { get; set; }
public string Status { get; set; }
}
Here is my controller code below.
public ActionResult Index()
{
MightyMouseContainer ctx = new MightyMouseContainer();
var NewList = new AuctionViewer
{
from CT in ctx.Categories
join PD in ctx.Items on CT.Category_ID equals PD.Category_ID
join AU in ctx.Auction_Schedule on PD.Item_ID equals AU.Item_ID
join ST in ctx.Status on AU.Status_ID equals ST.Status1
orderby AU.Auction_ID
select new
{
AuctionId = AU.Auction_ID,
ProductName = PD.Item_name,
Price= PD.Item_Value,
startTime = AU.Start_Time,
EndTime = AU.End_Time,
Category = CT.Category_Description,
Status = ST.Description
};
}
return View(NewList);
}
I wonder why is giving errors. please advise. I have been on this for quite a while and realized that I need some help to move on. I will appreciate prompt response in other to move forward. Thanks
Assuming your view accepts a model of IEnumerable<AuctionViewer>, you should change the select to return the strongly typed collection, e.g.:
var NewList = from CT in ctx.Categories
join PD in ctx.Items on CT.Category_ID equals PD.Category_ID
join AU in ctx.Auction_Schedule on PD.Item_ID equals AU.Item_ID
join ST in ctx.Status on AU.Status_ID equals ST.Status1
orderby AU.Auction_ID
select new AuctionViewer
{
AuctionId = AU.Auction_ID,
ProductName = PD.Item_name,
Price= PD.Item_Value,
startTime = AU.Start_Time,
EndTime = AU.End_Time,
Category = CT.Category_Description,
Status = ST.Description
};
return View(NewList);
Edit From your second error message, it seems that the view expects a List<AuctionViewer>. You can change the controller method to materialize the IQueryable as a List as follows:
var NewList = (from CT in ctx.Categories
join PD in ctx.Items on CT.Category_ID equals PD.Category_ID
join AU in ctx.Auction_Schedule on PD.Item_ID equals AU.Item_ID
join ST in ctx.Status on AU.Status_ID equals ST.Status1
orderby AU.Auction_ID
select new AuctionViewer
{
AuctionId = AU.Auction_ID,
ProductName = PD.Item_name,
Price= PD.Item_Value,
startTime = AU.Start_Time,
EndTime = AU.End_Time,
Category = CT.Category_Description,
Status = ST.Description
}).ToList();
return View(NewList);

Resources