Using textbox to enter value into database table Asp.net MVC - c#

I have a list of items that I pull from a database and at the same time I want the user to enter the quantity issued.
My problem is that after I click the button print/issue the amount in the database for quantity issued is 0.
I have added a TextBox for the user to enter the value. Not sure if what I have here is correctly done.
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
View
if (#Model.items.Count > 0)
{
foreach (var issueditem in #Model.items)
{
<tr>
<td class="col-md-4">#issueditem.itemNumber</td>
<td class="col-md-4">#issueditem.description</td>
<td class="col-md-4">#issueditem.expense_account.getDescription</td>
<td class="col-md-2">#issueditem.quantity.ToString()</td>
<td class="col-md-5">
#*#Html.LabelFor(model => model.item.quantityI, htmlAttributes: new { #class = "col-md-3" })*#
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
</td>
<td class="col-md-1">#issueditem.selecteduomtext </td>
<td class="col-md-1">#issueditem.price.ToString()</td>
</tr>
}
}
Controller
public ActionResult ReceiptPrint(Issue issue)
{
IssueDAO dbdata = new IssueDAO();
dbdata.connectionString = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
getIssue.transactionDate = DateTime.Now; //Sets the transaction date to current date
getIssue.status = -1;
getIssue.docType = "Issue";
ViewBag.StoresReps =dbdata.SelectEmployeesByDept("Stores");
getIssue.employeeDetails.employeeNum = issue.employeeDetails.employeeNum;
getIssue.processedbyDetails.employeeNum = issue.processedbyDetails.employeeNum;
getIssue.inventory_acccount=5520;
Item item = new Item();
try
{
dbdata.createIssue(getIssue, item);//Creates the issue in the database
}
catch (Exception ex)
{
LogWrite logWriter = new LogWrite(ex.ToString());
ViewBag.errorMessage = "Unable to complete the Issue. Please see Log file for more Information";
return View("IssueItem", getIssue);
}
DataSet ds = dbdata.GetReceipt(getIssue.requisitionNumber);
LocalReport localreport = new LocalReport();
localreport.ReportPath = Request.MapPath(Request.ApplicationPath) + #"Reports\Reciept.rdlc";
localreport.DataSources.Add(new ReportDataSource("Receipt_Data", ds.Tables[0]));
localreport.SetParameters(new ReportParameter("Req_num", getIssue.requisitionNumber));
string reporttype = "PDF";
string mimeType;
string encoding;
string fileNameExtension = "pdf";
string deviceInfo = #"<DeviceInfo>
<OutputFormat>PDF</OutputFormat>
<PageWidth>8.5in</PageWidth>
<PageHeight>11in</PageHeight>
<MarginTop>0.25in</MarginTop>
<MarginLeft>0.45in</MarginLeft>
<MarginRight>0.45in</MarginRight>
<MarginBottom>0.25in</MarginBottom></DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localreport.Render(
reporttype, deviceInfo, out mimeType, out encoding, out fileNameExtension,
out streams, out warnings);
var doc = new iTextSharp.text.Document();
var reader = new PdfReader(renderedBytes);
using (FileStream fs = new FileStream(Server.MapPath("~/Receipt" +
Convert.ToString(Session["CurrentUserName"]) + ".pdf"), FileMode.Create))
{
PdfStamper stamper = new PdfStamper(reader, fs);
string Printer = "Xerox Phaser 3635MFP PCL6";
// This is the script for automatically printing the pdf in acrobat viewer
stamper.JavaScript = "var pp = getPrintParams();pp.interactive =pp.constants.interactionLevel.automatic; pp.printerName = " +
Printer + ";print(pp);\r";
stamper.Close();
}
reader.Close();
FileStream fss = new FileStream(Server.MapPath("~/Receipt.pdf"), FileMode.Open);
byte[] bytes = new byte[fss.Length];
fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
fss.Close();
System.IO.File.Delete(Server.MapPath("~/Receipt.pdf"));
return File(bytes, "application/pdf", "receipt.pdf");
}

I can't see anywhere in your controller that you have updated or selected from the model the quantity. I See pulling data from the database, I see where your pushing to the database, but I don't see anywhere your setting the quantity.
Normally you'll have your view (with a begin form)
#using (Html.BeginForm("ActionMethodName","ControllerName"))
{
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
<input class="button" id="submit" type="submit" value="Submit" />
}
Then in your controller you'd have something to read the model data your passing back. There are three main ways to do this,
1) Using a public FormCollection
ActionResult ActionMethodName(FormCollection collection)
{
string quantity = collection.Get("quantityI);
}
2) Using direct named values
ActionResult ActionMethodNAme(string quantityI)
{
// The quantityI is already stored in the string parameter
}
3) Using a model view
ActionResult ActionMethodNAme(MyClass myItem)
{
// MyClass would be defined as a class containing all your variables pulled from the form so you could do. You need to make MyClass in advance!
string quantity = myItem.quantityI;
}

Related

Editor template for a datetime field issue (looses value on POST)

I'm trying to create an Editor Template for a DateTime field.
The display of the field works as it should, however when the field gets posted back top the server it looses its value. I'm using flatpickr for the date part and the time part.
My Class:
public class myClass
{
[Key]
public int Id { get; set; }
[UIHint("DateTime")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd HH:mm}")]
[DataType(DataType.DateTime)]
public DateTime MyDateTime { get; set; }
}
Controller:
public ActionResult Edit()
{
var myClass = new myClass
{
Id = 1,
MyDateTime = DateTime.Now,
};
ViewBag.Language = "en-US"; // "fr-FR"; //
ViewBag.MinDate = new DateTime(2022, 4, 1, 0, 0, 0).Date.ToString("yyyy-MM-dd");
ViewBag.MaxDate = DateTime.Today.Date.ToString("yyyy-MM-dd");
return View("Edit2", myClass);
}
View:
#model EditorTemplates.Models.myClass
#{
ViewBag.Title = "Edit2";
}
<h2>Edit2</h2>
#using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>myClass</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.MyDateTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MyDateTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MyDateTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Editor Template (DateTime.cshtml)
#* usage : #Html.EditorFor(m => m.BirthDate, new { Language = 'fr-FR', MinDate = '2022-04-01', MaxDate = '2022-04-05' }) *#
#model System.DateTime
#{
//var value = Model.ToString("yyyy-MM-dd [HH:mm]");
var yearPart = Model.Year.ToString("0000");
var monthPart = Model.Month.ToString("00");
var dayPart = Model.Day.ToString("00");
var datePart = $"{yearPart}-{monthPart}-{dayPart}";
var hourPart = Model.Hour.ToString("00");
var minutePart = Model.Minute.ToString("00");
const string secondPart = "00";
var timePart = $"{hourPart}:{minutePart}";
Console.WriteLine($"{datePart} [{hourPart}:{minutePart}:{secondPart}]");
}
<div class="input-group" style="width: 320px">
#Html.TextBox("date", datePart, new { #class = "form-control", #style = "min-width:220px", #id = "DatePart" })
^__i class="far fa-clock fa-1x" aria-hidden="true">
#Html.TextBox("time", timePart, new { #class = "form-control", #style = "min-width:80px; max-width:80px", #id = "TimePart" })
</div>
#Html.TextBox("value", Model, new { #id = "Value", #class = "form-control", #readonly ="readonly" })
<script type="text/javascript">
let locale = '#ViewBag.Language';
let altFormat = 'F j, Y';
if (locale === 'fr-FR') altFormat = 'j F Y';
flatpickr('#DatePart',
{
altFormat: altFormat, // Exactly the same as date format, but for the altInput field
altInput: true, // Show the user a readable date (as per altFormat), but return something totally different to the server.
allowInput: true,
allowInvalidPreload: true, // Allows the preloading of an invalid date. When disabled, the field will be cleared if the provided date is invalid
dateFormat: 'Y-m-d',
enableTime: false,
locale: '#ViewBag.Language',
minDate: '#ViewBag.MinDate',
maxDate: '#ViewBag.MaxDate',
onChange: function (selectedDates, dateStr, instance) {
console.log("onChange flatpickr date");
set();
}
});
flatpickr('#TimePart',
{
allowInput: true,
enableTime: true,
noCalendar: true,
dateFormat: "H:i",
time_24hr: true,
onChange: function (selectedDates, dateStr, instance) {
console.log("onChange flatpickr time");
set();
}
});
function set() {
let dmy = document.getElementById('DatePart').value;
console.log(`DatePart: ${dmy}`);
// remove time part
if (dmy.split(' ').length > 1) dmy = dmy.split(' ')[0];
//console.log(dmy);
let sep = '-';
if (dmy.split(sep).length !== 3) sep = '/';
const year = dmy.split(sep)[0];
const month = dmy.split(sep)[1];
const day = dmy.split(sep)[2];
//console.log(`${year}/${month}/${day}`);
//let hour = document.getElementById('HourPart').value;
//if (hour.length === 1) hour = `0${hour}`;
//let min = document.getElementById('MinutePart').value;
//if (min.length === 1) min = `0${min}`;
//console.log(`set: ${dmy} [${hour}:${min}]`);
const hm = document.getElementById('TimePart').value;
console.log(`TimePart: ${hm}`);
sep = ':';
const hour = hm.split(sep)[0];
const min = hm.split(sep)[1];
console.log(`Year : ${parseInt(year)}`);
console.log(`Month : ${parseInt(month)}`);
console.log(`Day : ${parseInt(day)}`);
console.log(`Hour : ${parseInt(hour)}`);
console.log(`Minute : ${parseInt(min)}`);
const dt = (`${year}-${month}-${day}`);
console.log(`date : ${dt}`);
const tm = (`${hour}:${min}`);
console.log(`time : ${tm}`);
const dtm = (`${month}/${day}/${year} ${hour}:${min}:00`);
console.log(`dtm : ${dtm}`);
const date = new Date(parseInt(year), parseInt(month)-1, parseInt(day), parseInt(hour), min);
console.log(`js date :${date}`);
document.getElementById("DatePart").value = dt;
//console.log(date.getHours() + ":" + date.getMinutes());
document.getElementById("TimePart").value = tm;
document.getElementById("Value").value = dtm;
};
</script>
I've tried several things, but each time the date gets posted to the controller as Jan 1st, 0001, [00:00].
The issue was that the model itself was not stored in the Editor Template:
once I replaced:
#Html.TextBox("value", Model, new { #id = "Value", #class = "form-control", #readonly ="readonly" })
by
#Html.HiddenFor(model => model, new { #id = #dateTimeId, #class = "form-control", #readonly = "readonly" })
I got the value back for the DateTime...

Populating Html.BeginForm drop down with data from HttpGet method

I am working with Jira Rest Api and I am trying to create a form that will include a dropdown with all the users from certain project, so I could assign them while creating a ticket.
My form works But unfortunnetly Users have to be hardcoded at the moment.
I am a novice programmer and my problem begins here: I am usign HttpPost to submit form and pass that values to Api, but before I do that I need to do HttpGet to populate one of the form dropdowns. This is confusing for me and I am not able to do that.
My Form
#using (Html.BeginForm("Index", "Ticket", FormMethod.Post))
{
<div>
<br />
<div style="background-color:#1976D2; color: white; padding: 3px; border-radius:3px; font-weight: 300;">
<a>Create Issue</a>
</div>
<br />
<form>
<span style="font-size: 0.9em">Project</span> #Html.DropDownListFor(m => model.fields.project.key, new List<SelectListItem> { new SelectListItem { Text = "Jira Test Board", Value = "JATP" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Issue type</span> #Html.DropDownListFor(m => model.fields.issuetype.name, new List<SelectListItem> { new SelectListItem { Text = "Sales", Value = "Sales" }, new SelectListItem { Text = "Bug", Value = "Bug" }, new SelectListItem { Text = "Feature", Value = "Feature" }, new SelectListItem { Text = "Task", Value = "Task" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Assign<sup class="star">*</sup></span> #Html.DropDownListFor(m => model.fields.assignee.name, new List<SelectListItem> { new SelectListItem { Text = "Jacob Zielinski", Value = "<someId>" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Summary<sup class="star">*</sup></span> #Html.TextBoxFor(m => model.fields.summary, new { #class = "form-control my-size-text-area input-background" })
<br />
<div class="form-group">
<span style="font-size: 0.9em">Description<sup class="star">*</sup></span> #Html.TextAreaFor(m => model.fields.description, 5, 60, new { #class = "form-control my-size-text-area input-background" })
</div>
<br />
<input onclick="loadingOverlay()" id="Submit" class="btn btn-primary float-right" type="submit" value="Create" />
</form>
</div>
}
Ticket Controller
public class TicketController : Controller
{
[HttpPost]
public async Task<ActionResult> Index(TokenRequestBody model)
{
var submitForm = new TokenRequestBody()
{
fields = new TokenRequestField()
{
project = model.fields.project,
description = model.fields.description,
summary = model.fields.summary,
issuetype = model.fields.issuetype,
assignee = model.fields.assignee
},
};
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"login:password")));
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = HttpMethod.Post;
httpRequestMessage.RequestUri = new Uri("<company>atlassian.net/rest/api/2/issue/");
httpRequestMessage.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(submitForm), Encoding.UTF8, "application/json");
var response = httpClient.SendAsync(httpRequestMessage).Result;
string responseBody = await response.Content.ReadAsStringAsync();
var jiraResponse = JsonConvert.DeserializeObject<TicketResponseBody>(responseBody);
TempData["Message"] = "Ticked Created";
TempData["Id"] = jiraResponse.Id;
TempData["Key"] = jiraResponse.Key;
TempData["Self"] = jiraResponse.Self;
return RedirectToAction("Index", "Home");
}
}
[HttpGet]
public async Task<ActionResult> GetUserToAssign()
{
using (var httpClient = new HttpClient())
{
var formatters = new List<MediaTypeFormatter>() {
new JsonMediaTypeFormatter(),
new XmlMediaTypeFormatter()
};
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"login:password")));
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = HttpMethod.Get;
var content = await httpClient.GetAsync("<company>atlassian.net/rest/api/2/user/assignable/search?project=HOP");
string responseBody = await content.Content.ReadAsStringAsync();
var assigneBodyResponse = new List<AssigneeRequestBody>();
var allUsersFromJira = await content.Content.ReadAsAsync<IEnumerable<AssigneeRequestBody>>(formatters);
var resultsJira = allUsersFromJira.Cast<AssigneeRequestBody>().ToList();
return View();
}
Home Controller
public ActionResult Index(LogFilterModelVm filterModel)
{
if (filterModel == null || filterModel.ResultCount == 0)
{
filterModel = new LogFilterModelVm() { CurrentPage = 0, ResultCount = 50, FromDate = DateTime.Now.AddDays(-7), ToDate = DateTime.Now };
}
using (var repositoryCollection = new repositoryCollection())
{
var logsFromDb = repositoryCollection.ErrorLogsRepository.AllErrorLogs(filterModel.CurrentPage, filterModel.ResultCount, filterModel.Filter_Source, filterModel.Filter_Type, filterModel.Filter_User, filterModel.Filter_Host, filterModel.Filter_SearchBar, filterModel.FromDate , filterModel.ToDate);
var chartCount = new List<int>();
var chartNames = new List<string>();
foreach(var item in logsFromDb.ChartData)
{
chartCount.Add(item.Count);
chartNames.Add(item.Source);
}
var viewModel = new LogPackageVm()
{
ChartCount = chartCount,
ChartNames = chartNames,
LogItems = logsFromDb.LogItems,
FilterModel = new LogFilterModelVm(),
Distinct_SourceLog = logsFromDb.Distinct_SourceLog,
Distinct_TypeLog = logsFromDb.Distinct_TypeLog,
Distinct_UserLog = logsFromDb.Distinct_UserLog,
Distinct_HostLog = logsFromDb.Distinct_HostLog,
Filter_SearchBar = logsFromDb.Filter_SearchBar,
};
return View(viewModel);
}
}
I have tried to return Get results to View Model but I have failed.
Above picture shows what is my expected result
Thanks to user #codein I have manage to do this.
I have call the Method within my HomeController
var users = await new TicketController().GetUserToAssign();
Created a ViewBag with SelectList
ViewBag.Users = new SelectList(users, "accountId", "displayName");
And called it on my View
#Html.DropDownListFor(m => model.fields.assignee.name, (IEnumerable<SelectListItem>)ViewBag.Users)
That works great for me.

db.SaveChanges not committing changes

I am connected with the ado.net entity model. I can retrieve information from the database using the Dropdownlist, but I am not able to commit changes (Insert) into the database. It previously works fine two days ago, but just stop working today. I have tried every trick in similar topics but no changes.
My Controlller:
public class RimySaleController : Controller
{
// GET: RimySale
// dropdownlist
public ActionResult RimSaleIndex()
{
newLayanDBEntities17 db = new newLayanDBEntities17();
List<Rim> list = db.Rims.ToList();
ViewBag.RimName = new SelectList(list, "rim_id", "rim_name");
List<Employee> lists = db.Employees.ToList();
ViewBag.EmpName = new SelectList(lists, "emp_id", "emp_name");
List<Customer> listp = db.Customers.ToList();
ViewBag.CustName = new SelectList(listp, "cust_id", "cust_name");
return View();
}
public ActionResult RimSaleSave(RimSale model)
{
try
{
newLayanDBEntities17 db = new newLayanDBEntities17();
Rim_Sale addRim = new Rim_Sale();
addRim.Date = model.Date;
addRim.cust_int = model.Cust_int;
addRim.emp_id = model.Emp_id;
addRim.rim_id = model.Rim_id;
addRim.rim_sold_quantity = model.Rim_sold_quantity;
addRim.rim_sold_unit_price = model.Rim_sold_unit_price;
//making the changes
db.Rim_Sale.Add(addRim);
db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RimSaleIndex");
}
}
}
My View:
#using (Html.BeginForm("SaveBattSale", "BatterySale", FormMethod.Post))
{
<br />
#Html.TextBoxFor(model => model.Sold_date, new { #type = "Date", #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Bat_id, ViewBag.BattName as SelectList, "--Select Battery--", new { #class = "form-control" })
<br />
#Html.TextBoxFor(model => model.Batt_sold_quantity, new { #type = "number", #placeholder = "Type Quantity Sold", #class = "form-control " })
<br />
#Html.TextBoxFor(model => model.Batt_unit_price, new { #placeholder = "Price Paid for One Battery", #type = "number", #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Cust_id, ViewBag.CustName as SelectList, "--Select Customer--", new { #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Emp_id, ViewBag.EmpName as SelectList, "--Select Employee--", new { #class = "form-control" })
<br />
<input type="Submit" value=" Submit" /> <input type="reset" value=" Reset" />
<br />
}
Your code looks ok. Try another one approach to insert data:
using (var db = new YourEntities())
{
Rim_Sale addRim = new Rim_Sale();
addRim.Date = model.Date;
addRim.cust_int = model.Cust_int;
addRim.emp_id = model.Emp_id;
addRim.rim_id = model.Rim_id;
addRim.rim_sold_quantity = model.Rim_sold_quantity;
addRim.rim_sold_unit_price = model.Rim_sold_unit_price;
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Rim_Sale] ON");
//making the changes
db.Rim_Sale.Add(addRim);
db.SaveChanges()
db.Entry(addRim).State = EntityState.Added;
db.SaveChanges();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Rim_Sale] OFF");
}
If data is not inserted, then there is a chance that you are inserting data to another database. If you use localDb, then make sure that a property of .mdf file in your solution as Copy to output Directory: "Copy only if newer", otherwise your db file will overwrite every time it runs.
UPDATE:
It is not a good way, but give a try:
db.Database.ExecuteSqlCommand(
"Insert into Rim_Sale Values(#Date, #cust_int, #emp_id, #rim_id,
#rim_sold_quantity , #rim_sold_unit_price )",
new SqlParameter("Date", Date),
new SqlParameter("cust_int", cust_int),
new SqlParameter("emp_id", emp_id),
new SqlParameter("rim_id", rim_id),
new SqlParameter("rim_sold_quantity ", rim_sold_quantity ),
new SqlParameter("rim_sold_unit_price ", rim_sold_unit_price ),
);

How to keep the id from the selectlist when using multiple columns in the textfield

I am trying to show multiple columns from my database in a dropdownlist using a SelectList
public ActionResult Create()
{
var times = db.Show_Courses
.Select(x =>
new {
id = x.show_course_id,
times = x.show_course_before + "," + x.show_course_after
});
ViewBag.course_id = new SelectList(times, "id", "times");
return View();
}
It shows up properly in the view but in the database the value of the id is 0
This was my code before i wanted to show two columns in the textfield of the selectlist
public ActionResult Create()
{
ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
return View();
}
And here is my code in the view
<div class="form-group">
#Html.LabelFor(model => model.course_show_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.course_show_id, "", new { #class = "text-danger" })
</div>
</div>
So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?
You could generate SelectList manually.
For example,
ViewBag.course_id = db.Show_Courses
.Select(x => new SelectListItem {
Text = x.show_course_before + "," + x.show_course_after,
Value = x.show_course_id.ToString() })
.ToList();
I personally like to use strongly type model. You can read more here
Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:
#Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })

How to bind value to dropdownlist in asp.net mvc?

I have several textboxes and one dropdownlist like:
for (int i = 0; i < count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #id = "ddlProjectvalue" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
</td>
}
and I want to bind data from database to all the fields , every thing is displaying data perfectly, but dropdown list for proj_id is not showing text even though i am passing value to dropdownlist. i am passing like :
public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
// GetimeSheet all the rows according employee name
var emps = (from n in db.TIMESHEETs
where n.RES_ID == empid
select n).ToList();
int count = emps.Count();
HttpContext.Current.Session["count"] = count;
try
{
List<TimesheetModel> emptyList = new List<TimesheetModel>();
TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.
//if Employee Name has more than one record.
if (emps.Count() > 0)
{
foreach (var timeSheet in emps)
{
TimesheetModel item = new TimesheetModel();
item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
item.PROJ_ID = timeSheet.PROJ_ID;
item.SUN_HRS = timeSheet.SUN_HRS;
item.MON_HRS = timeSheet.MON_HRS;
item.TUE_HRS = timeSheet.TUE_HRS;
item.WED_HRS = timeSheet.WED_HRS;
item.THU_HRS = timeSheet.THU_HRS;
item.FRI_HRS = timeSheet.FRI_HRS;
item.SAT_HRS = timeSheet.SAT_HRS;
TimesheetModel.GetTimeSheetDetails.Add(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
return count;
}
and returning to controller like :
public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
Employer_BL employerBL = new Employer_BL();
ViewBag.ProjectList = timesheetModel.getProjects;
//If GetTimesheetData returns morethan one record
if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
{
timesheetModel.EMP_ID = empId;
//passes model data to View
return View("Timesheet", timesheetModel);
}
TimesheetModel model = new TimesheetModel();
model.EMP_ID = empId;
return View("Timesheet", model);
}
Where am I doing wrong, dropdownlist showing initial index instead of showing text of passing values. Please help me anyone.
in Separate Class I have written like below to get project names:
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
It depends on the ViewBag.ProjectList which I cannot found on your source code. You could populate it with an object of type IEnumerable<SelectListItem> with one of the item Selected properties set to true.
public IEnumerable<SelectListItem> GetList()
{
return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
}
on your controller
ViewBag.ProjectList = GetList();
on your view
#{
var projectList =
new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
}
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")
You can try like this method:
[NonAction]
private IEnumerable<SelectListItem> GetData()
{
return new List<SelectListItem>()
{
new SelectListItem(){ Text="--Select--", Value="0"},
new SelectListItem(){ Text="A", Value="1"},
new SelectListItem(){ Text="B", Value="2"},
new SelectListItem(){ Text="C", Value="3"},
};
}
Call this function in Action Method
public ActionResult Create()
{
ViewData["categories"] = GetData();
return View();
}
On your html page:
<%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>
You can use viewbag . in your controller you can read your data from the database :
public ActionResult Create()
{
ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
}
And in your view model you can read the data from controller like this :
<div class="editor-label">
#Html.LabelFor(model => model.ClassId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
#Html.ValidationMessageFor(model => model.ClassId)
</div>
This code automatically binds ids of your data to DDL Here is class id.
This is th getClassList function :
public List<Class> GetClasslist()
{
return _dbcontext.Classes.ToList();
}

Categories