Date Formats in MVC - javascript

My view models and controllers seem to save the date time in a different format. For instance, in my view in the HTML text box, if I had entered in 07/12/2015, it would have saved the value as if it is "December 7, 2015". I am using the Boostrap Javascript DateTime Picker. (a side note: if I entered in the "dateFormat" for the datetime picker, the picker would not work, and that's why I commented out that line)
Is there a way such that I can change the saved format of the HTML text box?
My view model: (part)
<div class="form-group">
#Html.Label("Actual Completion Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Actual_Completion_Date, new { htmlAttributes = new { #Value = Model.Actual_Completion_Date, #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Actual_Completion_Date, "", new { #class = "text-danger" })
</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>
}
#section scripts {
<script type="text/javascript">
$(function () {
$('#Actual_Completion_Date').datetimepicker({
//dateFormat: "dd/mm/yyyy",
defaultDate: '#Model.Actual_Completion_Date',
format: 'L',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
});
$('#Actual_Completion_Date').datetimepicker({
defaultDate: '#Model.Actual_Completion_Date',
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
});
</script>
}
My model (part):
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_Assigned { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Actual_Completion_Date { get; set; }
Any advice or pointers? Many thanks in advance.

How datetime is parsed depends on the current language for posted values and values passed as querystring.
Values passed as part of the route are parsed using invariant culture. Check with f12 tools or Fiddler what kind of request you have.
If you want to change the behaviour you would change the curent culture for the thread (for posted values and querystrings) or register your own midelbinder (for route values)

Related

How to remove/hide time from jQuery DateTimePicker, Asp Net

I removed the time selection in the calendar widget and the start date in the fields also without time.
But the main problem is that when you select a date, the current time is still inserted in the field. Need only to display the date, without the time.
cshtml
<div class="form-group">
#Html.LabelFor(model => model.DateTo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateTo, "{0:d}", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateTo, "", new { #class = "text-danger" })
</div>
js
$("#DateTo").datetimepicker({
timepicker: false,
pickTime: false,
closeOnDateSelect: true,
dateFormat: "yy/mm/dd"
});
Model
[Display(Name = "DateTo", ResourceType = typeof(Resources.Resource))]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required]
public DateTime DateTo { get; set; }
jQuery DateTimePicker plugin v2.4.5
If there are simple alternative widgets for asp net, please advise.
To display only the date without the time, just do it this way:
$("#DateTo").datepicker({
dateFormat: "yy/mm/dd",
closeOnDateSelect: true
});
Because you're going through .datetimepicker where it picks up date and time, .datepicker picks up only thedate.

Submit values from razor view to a controller action which accept values by HTTP Post method

I have a view in one of my controller which have list of items. When user clicks each item, browser must navigate to page which brings details about this item.
Controller for Details accepts values through post method and have complex input object as its input.
Here is sample method for to navigate to details page using GET method to send values:
function openDetailsPage(commodityID, commodityName) {
dateFrom = convertNumbers2English('#(((FilterViewModel)ViewBag.ViewModel).dateValue_1)');
dateTo = convertNumbers2English('#(((FilterViewModel)ViewBag.ViewModel).dateValue_2)');
dateFrom = changeDateSeparator(dateFrom);
dateTo = changeDateSeparator(dateTo);
if (dateTo == null || dateTo == undefined)
dateTo = "0";
if (dateFrom == null || dateFrom == undefined)
dateFrom = "0";
#{
string reportTypes = "0";
if (((FilterViewModel)ViewBag.ViewModel).purchaseReportTypes != null)
{
reportTypes = String.Join(",", ((FilterViewModel)ViewBag.ViewModel).purchaseReportTypes);
}
}
alert('#reportTypes');
var url = '#Url.Action("ReportDetailed","BuyReport",new {
commodityType =(((FilterViewModel)ViewBag.ViewModel).commodityType),
commodityName="dummyCommodityName",
department=((FilterViewModel)ViewBag.ViewModel).department,
repository=((FilterViewModel)ViewBag.ViewModel).repository,
commodity ="dummyCommodityID",
purchaseReportTypes=reportTypes,
dateValue_1="dummyDate1",
dateValue_2="dummyDate2"
})';
alert(url);
#*var url = '#Url.Action("ReportDetailed","BuyReport",
new RouteValueDictionary
{
{"commodityType",((FilterViewModel)ViewBag.ViewModel).commodityType},
{"commodityName","dummyCommodityName" },
{"department",((FilterViewModel)ViewBag.ViewModel).department },
{"repository",((FilterViewModel)ViewBag.ViewModel).repository },
{"commodity","dummyCommodityID"},
{"purchaseReportTypes",((FilterViewModel)ViewBag.ViewModel).purchaseReportTypes },
{"dateValue_1",((FilterViewModel)ViewBag.ViewModel).dateValue_1 },
{ "dateValue_2",((FilterViewModel)ViewBag.ViewModel).dateValue_2 }
})';*#
url = url.replace("dummyCommodityID", commodityID);
url = url.replace("dummyCommodityName", commodityName);
url = url.replace("dummyDate1", dateFrom);
url = url.replace("dummyDate2", dateTo);
alert(url);
openLink(url);
}
I have some difficulties with this type of routing for values:
Input object is complex so route would be so complex. E.g. /BuyReport/ReportDetailed?commodityType=0&commodityName=dummyCommodityName&department=1&repository=2&commodity=dummyCommodityID&dateValue_1=dummyDate1&dateValue_2=dummyDate2 or /BuyReport/ReportDetailed/0/itemName/1/2/1/123/
Any special characters in get parameters such as / will break routing
I cannot pass stuff like arrays so I should convert them before sending
So I'm looking for a method to send parameters using 'Post' method like what form submit button does with below constraints:
I have no forms in my view
I want to post values to controller and page must navigate to details view
Each item in first page, have different row and different ID so I think creating a form for each row is not reasonable.
I want to know are there any ways to implement Post parameters according to my requirements? I would not care if it would be a mixture of C#, JS and jQuery.
More Details:
Here is a sample row in my list page which calls openDetailsPage js function:
<a onclick="openDetailsPage(#item.CommodityId,'#Html.DisplayFor(modelItem => item.CommodityName)')">
<div class="ios-content-box px-4 py-1 mb-3 ios-hover-box">
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 f-w-600 color-orange text-right">#Html.DisplayFor(modelItem => item.CommodityName)</div>
<div class="col-6 text-left"> <i class="fas fa-chevron-left fa-fw color-orange "></i></div>
</div>
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 text-gray-600 text-right">type</div>
<div class="col-6 text-gray-600 text-left">#Html.DisplayFor(modelItem => item.TypesName)</div>
</div>
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 text-gray-600 text-right">Code</div>
<div class="col-6 text-gray-600 text-left">#Html.DisplayFor(modelItem => item.CommodityCode)</div>
</div>
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 text-gray-600 text-right">Barcode</div>
<div class="col-6 text-gray-600 text-left">#Html.DisplayFor(modelItem => item.CommodityBarcode)</div>
</div>
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 text-gray-600 text-right">Unit Price</div>
<div class="col-6 text-gray-600 text-left">#Html.DisplayFor(modelItem => item.UnitPrice)</div>
</div>
<div class="row font-12 my-2 ios-divider-line">
<div class="col-6 text-gray-600 text-right">Total Price</div>
<div class="col-6 text-gray-600 text-left">#Html.DisplayFor(modelItem => item.SumPrice)</div>
</div>
</div>
</a>
Currently my controller is as below:
[Route("BuyReport/ReportDetailed/{commodityType}/{commodityName}/{department}/{repository}/{commodity}/{purchaseReportTypes}/{dateValue_1}/{dateValue_2}")]
public async Task<ActionResult> ReportDetailed(
string commodityType,
string commodityName,
string department,
string repository,
string commodity,
string purchaseReportTypes,
string dateValue_1,
string dateValue_2
)
{
}
But I want to change it to something like this:
[HttpPost]
public async Task<ActionResult> ReportDetailed(DetailedViewModel detailedviewmodel){
string commodity = detailedviewmodel.commodity;
string commoditytype = detailedviewmodel.commoditytype;
string department = detailedviewmodel.department;
string purchasereporttypes = detailedviewmodel.purchasereporttypes;
string repository = detailedviewmodel.repository;
string startdate = detailedviewmodel.datevalue_1;
string enddate = detailedviewmodel.datevalue_2;
string commdoityname = detailedviewmodel.commodityname;
}
Where DetailedViewModel is defined as below:
public class DetailedViewModel
{
public string commodityType { get; set; }
public string commodityName { get; set; }
public string department { get; set; }
public string repository { get; set; }
public string commodity { get; set; }
public string[] purchaseReportTypes { get; set; }
public string dateValue_1 { get; set; }//start date
public string dateValue_2 { get; set; }//end date
}
This is not the right way to meet your purpose. Your code looks vulnerable for exploiters too. Don't use solutions which break the normal web application behavior.
Instead, send the parameters to the corresponding controller method and then make an internal redirection with model passing (controller side). If your data is stored in database just send CommodityId and find details in controller side instead of sending entire details as form (HTTPPOST). In this way, you have a well designed project without unwanted crashes which come from breaking the behaviors and your code looks simple and clear as you want.
One quick simple solution is to post via Ajax:
Let's imagine this as your controller:
[HttpGet]
public ActionResult ReportDetailed()
{
return View();
}
[HttpPost]
public JsonResult ReportDetailed(DetailedViewModel detailedviewmodel)
{
var status = "error";
var message = "";
try
{
string commodity = detailedviewmodel.commodity;
string commoditytype = detailedviewmodel.commodityType;
string department = detailedviewmodel.department;
List<string> purchasereporttypes = detailedviewmodel.purchaseReportTypes;
string repository = detailedviewmodel.repository;
string startdate = detailedviewmodel.dateValue_2;
string enddate = detailedviewmodel.dateValue_1;
string commdoityname = detailedviewmodel.commodityName;
// your code here ...
status = "success";
return Json(new { status, detailedviewmodel } , JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
message = ex.Message;
return Json(new { status, message }, JsonRequestBehavior.AllowGet);
}
}
Assuming you have defined DetailedViewModel inside the Models folder:
public class DetailedViewModel
{
public string commodityType { get; set; }
public string commodityName { get; set; }
public string department { get; set; }
public string repository { get; set; }
public string commodity { get; set; }
public List<string> purchaseReportTypes { get; set; }
public string dateValue_1 { get; set; }//start date
public string dateValue_2 { get; set; }//end date
}
In your View, I copy the whole Html and Javascript for you, just grab it and tweak it to your needs:
#model Your_Proj_Namespace.Models.DetailedViewModel
#{
ViewBag.Title = "ReportDetailed";
}
<h2>ReportDetailed</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DetailedViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.commodityType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.commodityType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.commodityType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.commodityName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.commodityName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.commodityName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.department, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.department, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.department, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label>purchaseReportTypes: 3 inputs for example</label>
<div class="col-md-10">
<input type="text" name="purchaseReportTypes[0]" class="form-control inputPurchaseReportTypes " value="" />
<input type="text" name="purchaseReportTypes[1]" class="form-control inputPurchaseReportTypes " value="" />
<input type="text" name="purchaseReportTypes[2]" class="form-control inputPurchaseReportTypes " value="" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.repository, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.repository, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.repository, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.commodity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.commodity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.commodity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateValue_1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateValue_1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateValue_1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateValue_2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateValue_2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateValue_2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#section scripts{
<script>
$('#submit').click(function (e) {
e.preventDefault();
alert('form submitted');
var list = [];
$('.inputPurchaseReportTypes').each( function (key, value) {
list.push($(this).val());
});
const DATA = {
commodityType: $('#commodityType').val(),
commodityName: $('#commodityName').val(),
department: $('#department').val(),
repository: $('#repository').val(),
commodity: $('#commodity').val(),
purchaseReportTypes: list,
dateValue_1: $('#dateValue_1').val(),
dateValue_2: $('#dateValue_2').val(),
};
console.log(DATA);
$.ajax({
url: '/YourControllerName/ReportDetailed',
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(DATA),
success: function (result) {
alert('success');
console.log(result);
// your code here
}
});
});
</script>
}
If you prefer not to use Ajax, comment the javascript code above (all the code inside <script>), to post the form directly.
I built and debugged the above code. Feel free to test it.
Hope this helped.
Finally, You might find the following links useful:
https://www.tutorialsteacher.com/mvc/model-binding-in-asp.net-mvc
This link clearly shows how to handle the list of Authors inside a book viewmodel, similar to yours: http://codebuckets.com/2016/09/07/asp-net-mvc-and-binding-complex-objects-magic/
https://stackoverflow.com/a/16326290/4687359
I agree with the solution by #A. Nadjar
one more note
Use HttpGet if you want user to share the url and show same data as he see it to another user ,
if not? use HttpPost with one Object parameter,
because maybe there's a Nullable parameters the user won't search by so the url will be like this
BuyReport/ReportDetailed/dummyCommodityName/null/null/null/dummyCommodityID/null/2/0
or don't use this custom route [Route("BuyReport/ReportDetailed/{commodityType}/{commodityName}/{department}/{repository}/{commodity}/{purchaseReportTypes}/{dateValue_1}/{dateValue_2}")]
so he can use the Query String and pass only the keys => values he want

Bootstrap 3 DateTimePicker in EditorTemplate

Created an Editor Template to dynamically create time slots. Now I am unable to select the time with datetimepicker. Code below. The following code works when apart of the main view. Is it possible to use datetimepicker in an editortemplate?
#model Testing.Models.TimeSlot
<div class="form-group row">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #Value = DateTime.Now.ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px"} })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #Value = DateTime.Now.AddMinutes(15).ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$('#StartTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
});
$(function () {
$('#EndTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15
});
});
$('#StartTime').removeAttr("data-val-date");
$('#EndTime').removeAttr("data-val-date");
</script>
Sections are not supported in partials, and your scripts are never included in the html returned to the client. In any case, scripts should never be in partials (which is what an EditorTemplate is) - you are generating inline scripts, making it harder to debug and risk including multiple instances of the scripts.
Delete the #section Scripts{ ... } code from your EditorTemplate and move it to the main view or its layout. To make this a bit more flexible, I recommend you give the inputs a class name, and use that as a jQuery selector, rather that referring to each individual id (and therefore only one script is required).
In addition, you should never set the value attribute when using the HtmlHelper methods. The methods correctly generate the value from ModelState, ViewData and finally the model property in that order, and by setting the value attribute, you are screwing up model binding. Instead, set the values in the GET method before you pass the model to the view.
Your code to generate the datepicker should be just
#Html.EditorFor(m => m.StartTime, new { htmlAttributes = new { #class = "form-control datetimepicker" } })
or more simply
#Html.TextBoxFor(m => m.StartTime, new { #class = "form-control datetimepicker" })
and you can then style the width
.datetimepicker {
width: 100px;
}
and the the script in the view or layout will be just
$('.datetimepicker').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
Its also not clear why you want to attempt to remove client side validation using .removeAttr("data-val-date"), and doing so suggests a problem with your design. It also appears that you want to select a time only, in which case your property should be TimeSpan.

using jQuery UI Datepicker in MVC razor getting error

I am following this example to use jQuery UI Datepicker in my MVC project.
Model
[DataType(DataType.Date)]
public DateTime RequestDate { get; set; }
Razor
<div class="form-group">
#Html.LabelFor(model => model.RequestDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestDate)
#Html.ValidationMessageFor(model => model.RequestDate, "", new { #class = "text-danger" })
</div>
Then as per tutorial created Date helper and pasted this line
#Html.TextBox("", String.Format("{0:d}", (string)Model.ToShortDateString()), new { #class = "datefield", #type = "date" })
When i run the application, i get run time exception for above line. Model is null. I am not sure why? and How does it bind to my model?
Additional information: Cannot perform runtime binding on a null
reference
DatePickerReady.js
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datefield").datepicker();
});
}
I think your problem is caused by the casting part of (string)Model.ToShortDateString(), no need for the casting here as the ToShortDateString will return a string anyways. Try this instead:
#Html.TextBox("", String.Format("{0:d}", Model.ToShortDateString()),
new { #class = "datefield", #type = "date" })
And you need to make sure to name your editor template a name matching your data type (DateTime.cshtml in your case) or use the UIHint attribute if you like to customize the name, and make sure you add your template under the proper EditorTemplates folder.

DataBinding: 'System.String' does not contain a property with the name 'numeroGuia'

I am a newbie at ASP.net MVC5, my problem is this:
I am creating a partial view "AgregaGuia", in which I make a query to TblGuias model of a row that do not yet have "fechaRecepcionGuia", these guides are filled in a combobox and when selected this the guide fills all textbox in that view. However when running the application it generated the following error: DataBinding : 'System.String' does not Contain a property with the name 'numeroGuia'.
Could anyone help me please??
this is my model:
public partial class TblGuias
{
public TblGuias()
{
this.TblFactIC = new HashSet<TblFactIC>();
}
public string numeroGuia { get; set; }
public string companiaEnvios { get; set; }
public string destino { get; set; }
public decimal pesoGuia { get; set; }
public System.DateTime fechaEnvioGuia { get; set; }
public Nullable<System.DateTime> fechaRecepcionGuia { get; set; }
public string comprobante { get; set; }
public virtual ICollection<TblFactIC> TblFactIC { get; set; }
}
this is my controller:
public class vueInveEntrsController : Controller
{
public ActionResult AgregaGuia()
{
ViewData["guia"] = new SelectList(db.TblGuias.Where(g => g.fechaRecepcionGuia == null).Select((g => g.numeroGuia)),"numeroGuia", "companiaEnvios","destino","pesoGuia","fechaEnvioGuia");
return PartialView(db.TblGuias.ToList());
}
[HttpPost]
public ActionResult Action(string numero)
{
var query = from c in db.TblGuias
where c.numeroGuia == numero
select c;
return Json(query);
}
}
and my view is as follows:
#using (#Html.BeginForm("Action", "vueInveEntrs", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.Label("Seleccione Guia", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("numero", (SelectList)ViewData["guia"], new { onchange = "Action(this.value);", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("CompaƱia Envios", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("transporte", null, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Destino", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("destino", null, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Peso", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("peso", null, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Fecha Envio", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("fechaenvio", null, new { #class = "form-control" })
</div>
</div>
}
<script type="text/javascript">
function Action(numero) {
$.ajax({
url: '#Url.Action("Action", "vueInveEntrs")',
type: "POST",
data: { "numero": numero },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#transporte").val(vdata[0].companiaEnvios);
$("#destino").val(vdata[0].destino);
$("#peso").val(vdata[0].pesoGuia);
$("#fechaenvio").val(vdata[0].fechaEnvioGuia);
}
}
});
}
</script>
The problem is this line in your controller:
ViewData["guia"] = new SelectList(
db.TblGuias.Where(g => g.fechaRecepcionGuia == null).Select((g => g.numeroGuia)),
"numeroGuia", "companiaEnvios","destino","pesoGuia","fechaEnvioGuia");
You are not specifying the constructor parameters for SelectList properly. There are several different overloads, but I think the one you want is this one:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
The first parameter, items, represents the list of items that you want be rendered into <option> tags inside the <select>.
The second parameter, dataValueField, is the name of the property on the items in the enumerable which will become the value attribute inside each <option> tag.
Similarly, the third parameter, dataTextField, is the name of the property which will become the text displayed for each <option>.
So, if you change your code to the following, I think it should work:
ViewData["guia"] = new SelectList(
db.TblGuias.Where(g => g.fechaRecepcionGuia == null), "numeroGuia", "numeroGuia");
If you want different text to display in the dropdown list, change the third parameter to a different property from your TblGuias class.

Categories

Resources