im trying pass a object since View to controller as ViewModel. But some arrive field empty to controller. This fields are KeyValuePair and have not idea for pass it correctly to Controller.
This is my code:
Controller:
public ActionResult Index(SearchResultsViewModel searchResultsViewModel)
{
PassengerDataViewModel viewModel = new PassengerDataViewModel()
{
Request = searchResultsViewModel,
PassengerType = GetPassengerTypes(),
NumberPeople = GetNumberPeople()
};
return View("PassengerData", viewModel);
}
ViewModel:
public class SearchResultsViewModel
{
public SearchViewModel Request { get; set; }
public string SearchFlightDatesText { get; set; }
public string SearchPaxSelectionText { get; set; }
public KeyValuePair<string, string> DepartureStation { get; set; }
public KeyValuePair<string, string> ArrivalStation { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public DateTime SelectedDate { get; set; }
public int SelectedDay { get; set; }
public List<FlightsResponseDTO> Days { get; set; }
public KeyValuePair<string, string> DepartureStation2 { get; set; }
public KeyValuePair<string, string> ArrivalStation2 { get; set; }
public List<FlightsResponseDTO> Days2 { get; set; }
public DateTime BeginDate2 { get; set; }
public DateTime EndDate2 { get; set; }
public DateTime SelectedDate2 { get; set; }
public int SelectedDay2 { get; set; }
}
View Code
Post = function (path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
debugger;
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
debugger;
document.body.appendChild(form);
form.submit();
}
$("a.baseButton.yellowButton.mediumButton").click(function (event) {
//Comprobamos si esta seleccionado un vuelo
if(!checkIfFlightSelected()){
$('#error-dialog').dialog({
modal: true,
height: 130,
width: 360
});
event.preventDefault();
return false;
}
//--------------Inicio SearchViewModel ------------------------------
debugger;
var departureStation = "#Model.Request.SelectedOrigin1";
var arrivalStation = "#Model.Request.SelectedDestination1";
var departureDate = "#Model.Request.SelectedFlightDate1";
var departureStation2 = "#Model.Request.SelectedOrigin2";
var arrivalStation2 = "#Model.Request.SelectedDestination2";
var departureDate2 = "#Model.Request.SelectedFlightDate2";
var adults = "#Model.Request.NumAdults";
var childs = "#Model.Request.NumChilds";
var infants = "#Model.Request.NumInfants";
var residentOrFamily ="#Model.Request.SelectedResidentOrLargueFamilyDiscount";
var PassengersWithDiscount = "#Model.Request.NumPassengersWithSpecialDiscount";
var tipo = "#Model.Request.SelectedSearchType";
var searchViewModelRequest = {
SelectedSearchType: tipo,
SelectedOrigin1: departureStation,
SelectedDestination1: arrivalStation,
SelectedFlightDate1: departureDate,
Tipo:tipo,
//SelectedOrigin2: departureStation2,
//SelectedDestination2: arrivalStation2,
//SelectedFlightDate2: departureDate2,
NumAdults: adults,
NumChilds: childs,
NumInfants: infants,
SelectedResidentOrLargueFamilyDiscount: residentOrFamily,
NumPassengersWithSpecialDiscount: PassengersWithDiscount
};
//-------------------Fin SearchViewModel---------------------------------
//Inicio SearchResultsViewModel
//-----------Datos para obtenr datos seleccioandos------------------
var partsId = $("#availabilityTable0 :input:checked")[0].id.split('_');
var day = calendariCarregat.Days[partsId[1]];
var journey=day.Journeys[partsId[2]];
var departureDate = new Date(journey.JourneySellKey.split('~')[5].split(' ')[0]);
//var arrivalDate = new Date(journey.JourneySellKey.split('~')[7].split(' ')[0]);
var departureHourDate = journey.DepartureTimeString;
var arrivalHourDate = journey.ArrivalTimeString;
var departureDay;
var departureMonth;
if (departureDate.getUTCDate() + 1 < 10) {
departureDay = "0" + (departureDate.getUTCDate() + 1);
} else {
departureDay = (departureDate.getUTCDate() + 1);
}
if (departureDate.getUTCDate() + 1 < 10) {
departureMonth = "0" + (departureDate.getUTCMonth() + 1);
} else {
departureMonth = (departureDate.getUTCMonth() + 1);
}
var normalDepartureDate = (departureDay) + "/" + (departureMonth) + "/" + departureDate.getUTCFullYear();
//----------------------Fin datos seleccionados--------------
var searchFlightDatesText = "#Model.SearchFlightDatesText";
var searchPaxSelectionText = "#Model.SearchPaxSelectionText";
var departureStation = {
"Key": "#Model.DepartureStation.Key",
"Value": "#Model.DepartureStation.Value"
};
var arrivalStation = {
"Key": "#Model.ArrivalStation.Key",
"Value": "#Model.ArrivalStation.Value"
};
var beginDate = "#Model.BeginDate";
var endDate = "#Model.EndDate";
var selectedDate = normalDepartureDate;
var selectedDay = "#Model.SelectedDay";
var days = "#Model.Days";
//var departureStation2 = null;
//var arrivalStation2 = null;
//var days2 = null;
//var beginDate2 = null;
//var endDate2 = null;
//var selectedDate2 = null;
//var selectedDay2 = null;
var searchResultsViewModel = {
//Request: searchViewModelRequest.toString(),
"Request.SelectedOrigin1": searchViewModelRequest.SelectedOrigin1,
"Request.SelectedSearchType": searchViewModelRequest.Tipo,
"Request.SelectedDestination1": searchViewModelRequest.SelectedDestination1,
"Request.SelectedFlightDate1": searchViewModelRequest.SelectedFlightDate1,
"Request.NumAdults": searchViewModelRequest.NumAdults,
"Request.NumChilds": searchViewModelRequest.NumChilds,
"Request.NumInfants": searchViewModelRequest.NumInfants,
"Request.IncrementSelectedFlightDate1": 0,
"Request.SelectedResidentOrLargueFamilyDiscount": searchViewModelRequest.SelectedResidentOrLargueFamilyDiscount,
"Request.NumPassengersWithSpecialDiscount": searchViewModelRequest.NumPassengersWithSpecialDiscount,
SearchFlightDatesText: searchFlightDatesText,
SearchPaxSelectionText: searchPaxSelectionText,
"DepartureStation.Key": "test",
"DepartureStation.Value": "test",
"ArrivalStation": "{ [test, test]}",
BeginDate: beginDate,
EndDate: endDate,
SelectedDate: selectedDate,
SelectedDay: selectedDay,
Days: days,
"DepartureStation2.Key": "test",
"DepartureStation2.Value": "test",
};
//--------------Fin SearchResultsViewModel
MICESearcher.Post('#Url.Action("Index", "PassengerData")', (searchResultsViewModel));
});
i have tried it pass values of many ways to the KeyValuePair but i could not achieve it
Edit(solved):
finally thanks to #Daniel J.G, I could solve the problem by following this website ASP MVC.NET - how to bind KeyValuePair?
thank you all for the help!!
Related
I am new to web api and C#. I am creating a function where I am calling values from table which has 33 rows. the query is this:
Select * from T_SVRS_Reg_Trans
I have created a model where I have put out properties like so:
public class UserModel
{
public int ID { get; set; }
public string OrgUnit { get; set; }
public string TDC { get; set; }
public string CustCode { get; set; }
public string CustName { get; set; }
public string DestCode { get; set; }
public string EMV { get; set; }
public string Service { get; set; }
public string SPCCode { get; set; }
public string SPCode { get; set; }
public string Remarks { get; set; }
public int Stage { get; set; }
public string Cost { get; set; }
public string SAPUpdate { get; set; }
public string Active { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedOn { get; set; }
}
Now I am calling the table values to get added in these properties. My function for that is this:
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
UserModel objUserModel = new UserModel();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
}
}
return Ok(objUserModel);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
However I am noticing that only the last table value is added to the model and the rest of it is not. I want to add all 33 values in model form to the model mentioned. Is there any way to do this?
PLease help
}
You overwrite objUserModel each iteration. Create a new one inside the loop, add them to a List<UserModel>, returning that to your view.
Also consider dropping the archaic Hungarian notation (the "obj" prefix). Also consider using an ORM instead of mapping columns to properties using strings.
You should create a List or Array of type UserModel and adding items into it
try
{
List<UserModel> result = new List<UserModel>();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
UserModel objUserModel = new UserModel();
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
result.Add(objUserModel);
}
}
return Ok(result);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
You need to use the collection instead of single object UserModel.
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
List<UserModel> userModels = new List<UserModel>();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel()
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
userModels.Add(userModels);
}
}
return Ok(userModels);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
As you are expecting more than one row to be returned, you need to collect the rows as you iterate your result set into some sort of collection/list/array.
Try making a list of your UserModel
List<UserModel> objUserModels = new List<UserModel>();
And then adding each object to the list after each iteration of your for loop:
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel();
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
objUserModels.Add(objUserModel);
}
And then return your list of objects:
return Ok(objUserModels);
Good day
I'm new to MVC and database relationships.
So i am creating a system of services (product ordering) I understand that there must be a 1: N (One to Many) relationship since a customer can order many products.
I have 2 tables, the first table stores the data of the person requesting the service and the ID generated in this case the name of the variable is REQ_NO, and the second table stores the products requested by the customer.
My problem is the following, How can I assign the ID of the customer that is generated in the database to the products that it asks for, for example: If the customer is generated, ID 304 asks for 2 products, those products are assigned ID 304
NOTE:
TB_CS_TEST2 Is for customer data and req_no
TB_CS_TEST Is for products with req_no assigned form TB_CS_TEST2
Here is my code
Class
public partial class TB_CS_TEST2
{
public decimal REQ_NO { get; set; }
public string REQUESTOR_EMPNO { get; set; }
public string DEPT_CD { get; set; }
public string ORG_NAME { get; set; }
public string EMAIL_ID { get; set; }
public string APPROVER1 { get; set; }
public string APPROVER2 { get; set; }
public Nullable<decimal> TOTAL_AMOUNT { get; set; }
public Nullable<System.DateTime> REQUEST_DATE { get; set; }
public Nullable<System.DateTime> APPROVAL_DATE { get; set; }
public Nullable<System.DateTime> EVENT_DATE { get; set; }
public string EVENT_PLACE { get; set; }
public string PURPOSE { get; set; }
public string REMARKS { get; set; }
public string STATUS { get; set; }
public Nullable<System.DateTime> CRT_DATE { get; set; }
public string EXT { get; set; }
public virtual TB_CS_TEST TB_CS_TEST { get; set; }
}
public partial class TB_CS_TEST
{
public decimal REQ_NO { get; set; }
public Nullable<decimal> SEQ_NO { get; set; }
public Nullable<decimal> ITEM_ID { get; set; }
public Nullable<decimal> QUANTITY { get; set; }
public string UOM { get; set; }
public Nullable<decimal> UNIT_PRICE { get; set; }
public Nullable<decimal> EXTENDED_AMT { get; set; }
public Nullable<System.DateTime> CRT_DATE { get; set; }
public virtual TB_CS_TEST2 TB_CS_TEST2 { get; set; }
}
Controllers
public class DataHeaderController : Controller
{
//
// GET: /DataHeader/
public ActionResult DataHeader()
{
List<MvcApplication31.TB_CS_TEST2> hdr = new List<MvcApplication31.TB_CS_TEST2> { new TB_CS_TEST2 { REQ_NO = 0, REQUESTOR_EMPNO = "", DEPT_CD = "", ORG_NAME = "", EMAIL_ID = "", APPROVER1 = "", APPROVER2 = "", TOTAL_AMOUNT = 0, REQUEST_DATE = DateTime.Now, APPROVAL_DATE = DateTime.Now, EVENT_DATE = DateTime.Now, EVENT_PLACE = "", PURPOSE = "", REMARKS = "", STATUS = "", EXT = "" } };
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
return View(hdr);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DataHeader(List<MvcApplication31.TB_CS_TEST2> hdr)
{
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
if (ModelState.IsValid)
{
using (Entities cd = new Entities())
{
foreach (var p in hdr)
{
p.CRT_DATE = DateTime.Now;
cd.TB_CS_TEST2.Add(p);
}
cd.SaveChanges();
ModelState.Clear();
hdr = new List<MvcApplication31.TB_CS_TEST2> { new TB_CS_TEST2 { REQ_NO = 0, REQUESTOR_EMPNO = "", DEPT_CD = "", ORG_NAME = "", EMAIL_ID = "", APPROVER1 = "", APPROVER2 = "", TOTAL_AMOUNT = 0, REQUEST_DATE = DateTime.Now, APPROVAL_DATE = DateTime.Now, EVENT_DATE = DateTime.Now, EVENT_PLACE = "", PURPOSE = "", REMARKS = "", STATUS = "", EXT = "" } };
}
}
return View(hdr);
}
}
public class BulkController : Controller
{
//
// GET: /Bulk/
public ActionResult Bulk()
{
//List<MvcApplication31.TB_CS_TEST> ci = new List<MvcApplication31.TB_CS_TEST> { new TB_CS_TEST { REQ = 0, CONTACTNO = "", CONTACTPERSON = "" } };
List<MvcApplication31.TB_CS_TEST> ci = new List<MvcApplication31.TB_CS_TEST> { new TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
IEnumerable<SelectListItem> listproduct = db.TB_POS_PRODUCTS.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.DESCRIPTION
}
);
ViewData["PRODUCTS"] = new SelectList(db.TB_POS_PRODUCTS, "ID", "DESCRIPTION");
//ViewData["DESCRIPTION"] = listproduct;
return View(ci);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bulk(List<MvcApplication31.TB_CS_TEST> ci)
{
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
IEnumerable<SelectListItem> listproduct = db.TB_POS_PRODUCTS.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.DESCRIPTION
}
);
ViewData["PRODUCTS"] = new SelectList(db.TB_POS_PRODUCTS, "ID", "DESCRIPTION");
//ViewData["DESCRIPTION"] = listproduct;
if (ModelState.IsValid)
{
using (Entities dc = new Entities())
{
foreach (var i in ci)
{
i.CRT_DATE = DateTime.Now;
dc.TB_CS_TEST.Add(i);
}
dc.SaveChanges();
ViewBag.Message = "Data Successfully saved!";
ModelState.Clear();
//ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { CONTACTID = 0, CONTACTNO = "", CONTACTPERSON = "" } };
ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
}
}
return View(ci);
}
}
Thanks for your help!
For experience i do the next steps.
if (ModelState.IsValid)
{
using (Entities dc = new Entities())
{
//decimal dcr = dc.TB_CS_TEST2.DefaultIfEmpty().Max(u => u.REQ_NO); THIS CODE PASS DE ID FROM THE OTHER TABLE AND PUT IN A VARIABLE AND USE IN SAVECHANGES
foreach (var i in ci)
{
decimal dcr = dc.TB_CS_TEST2.DefaultIfEmpty().Max(u => u.REQ_NO);
i.REQ_NO = dcr;
i.CRT_DATE = DateTime.Now;
dc.TB_CS_TEST.Add(i);
}
//var cust = new TB_CS_TEST2();
//var pedido = new TB_CS_TEST { TB_CS_TEST2 = cust };
dc.SaveChanges();
SendEmail();
if (dc.SaveChanges() > 0)
{
ViewBag.Message = "Data Successfully saved!";
}
else
{
ViewBag.Message = "Error";
}
ModelState.Clear();
//ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { CONTACTID = 0, CONTACTNO = "", CONTACTPERSON = "" } };
ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
}
}
return View(ci);
I am using Pagedlist for Pagination in my MVC project. Pagination is working for most of the cases without ViewModels.
But when I use a ViewModel PagedList generating Pagination links but without any parameter value to querystring page.
Here is my ViewModel
public class SearchResult
{
public int ItemID { get; set; }
public string ItemTitle { get; set; }
public int? AuthorID { get; set; }
public string AuthorName { get; set; }
public int? IssueDate { get; set; }
}
And ActionResult Method
public ActionResult Date(int? page)
{
try
{
string query;
if (Request.RequestContext.RouteData.Values["query"] != null)
{
using (dreposEntities db = new dreposEntities())
{
query = Request.RequestContext.RouteData.Values["query"].ToString();
int issueYear = int.Parse(query);
ViewBag.Query = issueYear;
var dateFilter = db.itemstreams.Where(q => q.issuedate == issueYear).ToList();
List<SearchResult> resultList = new List<SearchResult>();
if (dateFilter.Any())
{
foreach (var c in dateFilter)
{
SearchResult obj = new SearchResult
{
ItemID = c.id,
ItemTitle = c.title,
IssueDate = c.issuedate,
};
resultList.Add(obj);
}
}
ViewBag.SearchQuery = query;
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
else
{
using (dreposEntities db = new dreposEntities())
{
List<SearchResult> resultList = new List<SearchResult>();
var files = db.itemstreams.Where(s=>s.status==1).ToList();
if (files.Any())
{
foreach (var f in files)
{
SearchResult obj = new SearchResult
{
ItemID = f.id,
ItemTitle = f.title,
IssueDate = f.issuedate,
};
resultList.Add(obj);
}
}
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
}
catch (Exception e)
{
return View();
}
}
What above code is showing in View is attached in below email
And in View/Razor
<div class="pull-right">
#Html.PagedListPager(Model, page => Url.Action("Date", new { page }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
</div>
I am a C# beginner programmer. I have a text file, which is my source, with multiple rows of data. I want to create one xml file with multiple xml documents inside the file. The xml documents are generated from the rows of data in the text file. I can only get one xml document to generate in the A0x.xml file that is created. My code only reads the first row of data and generates one xml document instead to multiple xml documents. Below are 8 rows from the M24EX.txt file. Please help!!
A0ASMSS3110004624190 EA00008FB239980940001RAIR A30 0120505 18094133644FT
A0ASMSS5340011122822 HD00001FB239981000001RAIR A6C 0120503 18100124741FT
A0ASMSS5365002870093 EA00003FB239981000002RAIR A6C 0120503 18100125431FT
A0ASMS 5365001671717 EA00005FB239981010001REY2550A6C 0120503133 18101075536SF
A0ASMS 5365001671717 EA00011FB239981010002RGE A6C 0120505129 18101105015FT
A0AFLZ 6625013922071 EA00001FB239981070001RGRN D6C 0120505110 18107150014FT
A0AFLZ 6650013204283 EA00003FB239981070002NGRN D6C 0120504777 18107151015FT
A0ASMSS1650009937278 EA00006FB239981080001RAIR A6C 0120505 18108082906FT
And the code:
Public class Program
{
public static void Main(string[] arg)
{
XDocument A0x = new XDocument();
var IdCode = "511";
var CtrlNbr = "0001";
var PurposeCode = "00";
var TypeCode = "A0";
var EntyIdCode = "OB";
var IdCodeQlfr = "10";
var EntyIdCode1 = "FR";
var DocNbr = "TN";
var AssignNbr = "1";
var NSN = "FS";
var DD = "74";
var AgncyQlfrCode = "DF";
var LstQlfrCode = "0";
DateTime saveUtcNow = DateTime.UtcNow;
DateTime saveNow = DateTime.Now;
var field = new ParseTextFile().Parse();
var tagBuilder = new TagBuilder();
var parent = tagBuilder.BuildParent("File");
var subParent = tagBuilder.BuildParent("T_Requisition_511");
var ParentST = tagBuilder.BuildParent("S_Transaction_Set_Header");
var ST01 = tagBuilder.BuildChild("E_Transaction_Set_Identifier_Code", IdCode);
var ST02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
var ParentBR = tagBuilder.BuildParent("S_Beginning_Segment_for_Material_Management");
var BR01 = tagBuilder.BuildChild("E_Transaction_Set_Purpose_Code", PurposeCode);
var BR02 = tagBuilder.BuildChild("E_Transaction_Type_Code", TypeCode);
var BR03 = tagBuilder.BuildChild("E_Date", saveUtcNow.ToString("yyyyMMdd"));
var BR09 = tagBuilder.BuildChild("E_Time", saveUtcNow.ToString("hhmmss"));
var ParentN1 = tagBuilder.BuildParent("L_Name");
var ParentS = tagBuilder.BuildParent("S_Name");
var N101 = tagBuilder.BuildChild("E_Entity_Identifier_Code", EntyIdCode);
var N103 = tagBuilder.BuildChild("E_Identification_Code_Qualifier", IdCodeQlfr);
var N104 = tagBuilder.BuildChild("E_Identification_Code", field.SRAN);
var N106 = tagBuilder.BuildChild("E_Entity_Identifier_Code_1", EntyIdCode1);
var ParentLX = tagBuilder.BuildParent("L_Assigned_Number");
var ParentAN = tagBuilder.BuildParent("S_Assigned_Number");
var LX01 = tagBuilder.BuildChild("E_Assigned_Number", AssignNbr);
var ParentN9 = tagBuilder.BuildParent("S_Reference_Identification");
var N901 = tagBuilder.BuildChild("E_Reference_Identification_Qualifier", DocNbr);
var N902 = tagBuilder.BuildChild("E_Reference_Identification", field.DocumentNumber);
var ParentPO1 = tagBuilder.BuildParent("S_Baseline_Item_Data");
var PO102 = tagBuilder.BuildChild("E_Quantity_Ordered", Convert.ToString(field.Quantity));
var PO103 = tagBuilder.BuildChild("E_Unit_or_Basis_for_Measurement_Code", field.UnitofIssue);
var PO106 = tagBuilder.BuildChild("E_Product_Service_ID_Qualifier", NSN);
var PO107 = tagBuilder.BuildChild("E_Product_Service_ID", field.StockNumber);
var ParentSE = tagBuilder.BuildParent("S_Transaction_Set_Trailer");
var SE01 = tagBuilder.BuildChild("E_Number_of_Included_Segments", new CountSegmentTags().CountSgmts().ToString());
var SE02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
parent.Add(subParent);
subParent.Add(ParentST);
ParentST.Add(ST01);
ParentST.Add(ST02);
subParent.Add(ParentBR);
ParentBR.Add(BR01);
ParentBR.Add(BR02);
ParentBR.Add(BR03);
ParentBR.Add(BR09);
subParent.Add(ParentN1);
ParentN1.Add(ParentS);
ParentS.Add(N101);
ParentS.Add(N103);
ParentS.Add(N104);
ParentS.Add(N106);
subParent.Add(ParentLX);
ParentLX.Add(ParentAN);
ParentAN.Add(LX01);
ParentLX.Add(ParentN9);
ParentN9.Add(N901);
ParentN9.Add(N902);
ParentLX.Add(ParentPO1);
ParentPO1.Add(PO102);
ParentPO1.Add(PO103);
ParentPO1.Add(PO106);
ParentPO1.Add(PO107);
ParentSE.Add(SE01);
ParentSE.Add(SE02);
A0x.Add(parent);
A0x.Declaration = new XDeclaration("1.0", "utf-8", "true");
A0x.Save("M24EX.xml");
}
public class TagBuilder
{
public XElement BuildParent(string name)
{
return new XElement(name);
}
public XElement BuildChild(string name, string value)
{
var tag = new XElement(name);
tag.Add(value);
return tag;
}
}
public void Read()
{
int counter = 0;
string line;
StreamReader file = new StreamReader("M24EX.txt");
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0")) // only pull "A0x" records
{
counter++;
Console.WriteLine("{0}:{1}", counter, line);
}
file.Close();
}
public class ParseTextFile
{
public TransactionFields Parse()
{
StreamReader file = new StreamReader("M24Ex.txt");
string line;
int counter = 0;
var field = new TransactionFields();
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0"))
{
//Assigns field to the Transaction field names
field.DocumentIdentifier = line.Substring(0, 3).Trim(); // Tric
field.RoutingIdentifier = line.Substring(4, 3).Trim();
field.MediaStatusCode = line.Substring(7, 1).Trim();
field.StockNumber = line.Substring(7, 15).Trim();
field.UnitofIssue = line.Substring(22, 2).Trim();
field.Quantity = Convert.ToInt32(line.Substring(24, 5));
field.DocumentNumber = line.Substring(29, 14).Trim();
field.SRAN = line.Substring(29, 6).Trim();
field.DemandCode = line.Substring(44, 1).Trim();
field.SupplementaryAddress = line.Substring(45, 6).Trim();
field.SignalCode = line.Substring(51, 1).Trim();
field.FundCode = line.Substring(52, 2).Trim();
field.DistributionCode = line.Substring(54, 3).Trim();
field.ProjectCode = line.Substring(57, 3).Trim();
field.Priority = line.Substring(60, 2).Trim();
field.ReqDeliveryDate = line.Substring(62, 3).Trim();
field.AdviceCode = line.Substring(65, 2).Trim();
field.DateReceiptofReq = line.Substring(67, 3).Trim();
field.PurposeCode = line.Substring(70, 1).Trim();
field.ConditionCode = line.Substring(71, 1).Trim();
field.MgmtCode = line.Substring(72, 1).Trim();
}
file.Close();
return field;
}
}
public class ConvertXmlToText
{
public void ConvertXmlDoc()
{
string onlyContent = string.Empty;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("A0x.xml");
var file = xdoc.SelectNodes("File/T_Requisition_511");
for (int i = 0; i < file.Count; i++)
{
onlyContent += string.Format("\n", i);
foreach (XmlNode node in file[i].ChildNodes)
onlyContent += string.Format("{0},", node.InnerText);
}
File.WriteAllText("A0x.txt", onlyContent);
}
}
public class TransactionFields
{
public string DocumentIdentifier { get; set; }
public string RoutingIdentifier { get; set; }
public string MediaStatusCode { get; set; }
public string StockNumber { get; set; }
public string UnitofIssue { get; set; }
public int Quantity { get; set; }
public string DocumentNumber { get; set; }
public string SRAN { get; set; }
public string DemandCode { get; set; }
public string SupplementaryAddress { get; set; }
public string SignalCode { get; set; }
public string FundCode { get; set; }
public string DistributionCode { get; set; }
public string ProjectCode { get; set; }
public string Priority { get; set; }
public double UnitPrice { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}
I have a block of code that preps a query here:
var AssetTagParam = new SQLiteParameter("#AssetTagParam", SqlDbType.Int) { Value = item.AssetTag };
var VendorParam = new SQLiteParameter("#VendorParam", SqlDbType.Text) { Value = item.Vendor };
var DeviceParam = new SQLiteParameter("#DeviceParam", SqlDbType.Text) { Value = item.Device };
var AttributeParam = new SQLiteParameter("#AttributeParam", SqlDbType.Text) { Value = item.Attribute };
var DeviceTypeParam = new SQLiteParameter("#DeviceTypeParam", SqlDbType.Text) { Value = item.DeviceType };
var SystemParam = new SQLiteParameter("#SystemParam", SqlDbType.Text) { Value = item.System };
var LocationParam = new SQLiteParameter("#LocationParam", SqlDbType.Text) { Value = item.Location };
var OnLoanParam = new SQLiteParameter("#OnLoanParam", SqlDbType.Binary) { Value = item.OnLoan };
var NotesParam = new SQLiteParameter("#NotesParam", SqlDbType.Text) { Value = item.Notes };
var LastModifiedTimeParam = new SQLiteParameter("#LastModifiedTimeParam", SqlDbType.Text) { Value = item.LastModifiedTime };
var LastModifiedPersonParam = new SQLiteParameter("#LastModifiedPersonParam", SqlDbType.Text) { Value = item.LastModifiedPerson };
var IsDeletedParam = new SQLiteParameter("#IsDeletedParam", SqlDbType.Binary) { Value = item.IsDeleted };
SQLiteCommand insertSQL = new SQLiteCommand("INSERT INTO Inventory(AssetTag, Vendor, Device, Attribute, DeviceType, System, Notes, OnLoan, Location)" +
" VALUES (#AssetTagParam, #VendorParam, #DeviceParam, #AttributeParam, #DeviceTypeParam, #SystemParam, #NotesParam, #OnLoanParam, #LocationParam)", conn);
insertSQL.Parameters.Add(AssetTagParam);
insertSQL.Parameters.Add(VendorParam);
insertSQL.Parameters.Add(DeviceParam);
insertSQL.Parameters.Add(AttributeParam);
insertSQL.Parameters.Add(DeviceTypeParam);
insertSQL.Parameters.Add(SystemParam);
insertSQL.Parameters.Add(LocationParam);
insertSQL.Parameters.Add(OnLoanParam);
insertSQL.Parameters.Add(NotesParam);
insertSQL.Parameters.Add(LastModifiedTimeParam);
insertSQL.Parameters.Add(LastModifiedPersonParam);
insertSQL.Parameters.Add(IsDeletedParam);
For Reference, the Item class looks like this:
public class Item
{
public int AssetID { get; set; }
public int AssetTag { get; set; }
public string Vendor { get; set; }
public string Device { get; set; }
public string Attribute { get; set; }
public string DeviceType { get; set; }
public string System { get; set; }
public string Location { get; set; }
public bool OnLoan { get; set; }
public string Notes { get; set; }
public string LastModifiedTime { get; set; }
public string LastModifiedPerson { get; set; }
public bool IsDeleted { get; set; }
}
When I run this code, I will always run into the generic error:
Input string was not in a correct format.
After trying to figure out the source of this issue, assuming that I typed something wrong in the process, I ran into the issue that all my Param vars had their dbType set to Int32. I thought I was setting with the parameter SqlDbType.Text, but I must be misunderstanding this?
How do I set the dbtype of my inputs to Text instead of Int32?
The mistake I was making is using SqlDbType to define the type of data. I should have been using System.Data.DbType to define the data, so this:
var VendorParam = new SQLiteParameter("#VendorParam", SqlDbType.Text) { Value = item.Vendor };
Should instead be changed to this:
var VendorParam = new SQLiteParameter("#VendorParam", System.Data.DbType.String) { Value = item.Vendor };