Why isn't my EditorFor datepicker field populating my value? - c#

I'm trying to get this datepicker field to populate with today's date but it's not happening for some reason. I can't find a reference for what options are accepted in the "new {}" section.
#Html.LabelFor(d => d.ServiceOn, new { #class = "control-label" })
#Html.EditorFor(d => d.ServiceOn, "DatePicker", new { disableMinDate = true, Value = DateTime.Today })
#Html.ValidationMessageFor(d => d.ServiceOn, "", new { #class = "text-danger" })
I've tried value, Value and #Value but the resulting html always shows value="". I'm wondering if maybe the datepicker itself is zeroing out the field. I feel like I'm missing something obvious here.

This should work:
#Html.LabelFor(d => d.ServiceOn, new { #class = "control-label" })
#{Model.ServiceOn= DateTime.Today;}
#Html.EditorFor(d => d.ServiceOn, "DatePicker", new { disableMinDate = true })
#Html.ValidationMessageFor(d => d.ServiceOn, "", new { #class = "text-danger" })
HTML work with the ModelState, not from the model itself.
If you want more loose helpers, ise #Html.Editor instead.

Related

Select all items in listbox on page load

In my MVC application, I am retrieving a list of objects based on an ID and stuffing those objects into a Listbox via a SelectList. Here is what I have:
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text");
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, (SelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", #class = "form-control" })
On page load, the listbox is filled with the correct options, except that they're not selected. Is there a way to do this without looping (which is what I've seen in other posts)?
Any help is appreciated.
UPDATE
I've edited a few things, along with added a line of code.
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID));
ViewBag.SpecCatIds = db.TBL_AssocIncidentSpecialCat.Where(x => x.IncidentId == incidentVm.ID)
.Select(x => x.SpecialCategoriesId).ToList();
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, new MultiSelectList(ViewBag.SpecCatListBox, "Value", "Text", ViewBag.SpecCatIds), new { id = "SpecialCat-ListBox", #class = "form-control" })
This is selecting all of the options as needed, but is there a way to not use 2 Viewbag objects?
I have figured this out.
C#
ViewBag.SpecCatListBox = new MultiSelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID).Select(x => x.Value));
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, (MultiSelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", #class = "form-control" })

How to hide #Html.DropDownList if ViewBag is null or empty

I have #Html.DropDownList which take data from controller in edit mode. I need to hide DropDown element and show some message if list is null or empty.
I try with this code in view, but all the time give me result thet have, and show empty dropdown:
#if(ViewBag.DatumRID != null)
{
<div class="col-md-10">
#Html.DropDownList("DatumRID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DatumRID, "", new { #class = "text-danger" })
</div>
}
else
{
<h6 style="color:#ff0000"> NO RECORDS.</h6>
}
And code from controller is here:
ViewBag.DatumRID = new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID);
when record fount dropdown is ok, but when record is null dropdown show empty.
Check list size also. For correct displaying data SelectList must contain more than zero items. Try this:
#if(ViewBag.DatumRID != null && ViewBag.DatumRID.Count > 0)
{
<div class="col-md-10">
#Html.DropDownList("DatumRID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DatumRID, "", new { #class = "text-danger" })
</div>
}
else
{
<h6 style="color:#ff0000"> NO RECORDS.</h6>
}
Update:
U may try update your controller code like this:
List<SelectListItem> viewList = new List<SelectListItem>();
viewList.AddRange(new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID));
ViewBag.DatumRID = viewList;
And pass "viewList" object to DropDownList helper at razor markup.
Ok. I searched around, and could find anything reasonable to work with. Selectlists don't have a Count() or any() method like most lists. Here's what I came up with:
#{
var counter=0;
foreach(var a in Viewbag.DatumRID)
{
counter++;
break; //stop it so it doesn't iterate through the whole thing since that's unnecessary
}
}
#if(counter>0){//put your dropdown here}

AJAX call from keydown on one text box to populate another text box ASP.NET MVC

I am attempting to populate a textbox from the value in a separate textbox, ie. using the customer account number to auto-populate the customer name. My AJAX is returning the proper results, however it's not getting populated into the other textbox, which is why I suspect my jQuery is wrong.
<div class="form-group">
#Html.LabelFor(model => model.AccountNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.AccountNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AccountNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
[HttpGet]
public ActionResult GetCustomerName(string RecKey)
{
var result = (from c in db.Customers
where c.RecKey.Equals(RecKey)
select new { c.RecName });
return Json(result, JsonRequestBehavior.AllowGet);
}
Returned JSON (only returning one result that's an exact match):
[{"RecName":"This is a customer name"}]
$(document).ready(function () {
var RecKey;
$(function () {
$("#AccountNumber").keydown(function () {
RecKey = $("#AccountNumber").val();
$.ajax({
type: "GET",
url: 'GetCustomerName',
data: { RecKey: RecKey },
success: function (data) {
if (data) {
//alert(data);
$('#CustomerName').val(data.RecName);
}
}
});
});
});
});
I am rather new to jQuery and have had success with autocomplete on the same textbox, however my searching hasn't found much for me to populate other text boxes. Anyone have any ideas?
The issue is because the resulting JSON is an array of objects. If you can guarantee that it will only ever return a single object within that array then you can hard-code the index accessor of the array:
success: function (data) {
if (data) {
$('#CustomerName').val(data[0].RecName);
}
}
Alternatively you can amend your C# code to return a single entity instead of an array:
return Json(result.SingleOrDefault(), JsonRequestBehavior.AllowGet); // or FirstOrDefault()
I think the TextBox helpers only add the name attribute, while your JQuery code is looking for the box by ID....
Try changing;
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control" })
to
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control", id = "CustomerName" })
You will also need to use either the SingleOrDefault server side or [0] indexer client side as suggested in the other answers - because even though the array only has one item, it is still an array (not an object) so that will need fixed as well.
P.S. A useful tool in debugging stuff like this is pressing F12 to get the developer console up - you can then try typing your jquery code to see if it works directly into the console. As an example if you type $("#CustomerName") do you actually get an object returned? If not - then my answer is the reason why. If so - something else is affecting this.

How to Show the value in textbox based on selection of item from dropdown list in mvc4?

How do I update my textboxes to display the Email1 and Mobile1 properties of my Contact model based on the selected value in a dropdownlist
View
#Html.LabelFor(model => model.CustomerName , new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #style = "width:250px;" })
#Html.LabelFor(model => model.Email1, new { #class = "control-label" })
#Html.TextBoxFor(model => model.ContactID, new { #class = "form-control", type = "text" })
#Html.ValidationMessageFor(model => model.Email1)
#Html.LabelFor(model => model.MobileNo1, new { #class = "control-label" })
#Html.TextBoxFor(model => model.ContactID, new { #class = "form-control", type = "text" })
#Html.ValidationMessageFor(model => model.MobileNo1)
Script
$('#CustomerContactID').change(function () {
$('#ContactID').empty();
$.ajax({
type: "GET",
url: "/VisitorsForm/GetEmailByCustomerContactId",
datatype: "Json",
data: { CustomerContactID: $('#CustomerContactID').val() },
success: function (data) {
$('#Email1').val(data.Email1);
$('#MobileNo1').val(data.Mobile1);
}
});
});
Controller
public JsonResult GetEmailByCustomerContactId(string CustomerContactId)
{
Guid Id = Guid.Parse(CustomerContactId);
var contacts = from a in db.Contacts where a.ContactID == Id select a;
return Json(contacts);
}
Your query in the GetEmailByCustomerContactId() returns IEnumerable<Contact>, a collection, not a single object, so data in the ajax success call back is an array and $('#Email1').val(data.Email1); fails because an array does not have a property named Email1 (but each item in the collection does)
Since you only want to return one Contact, change your query to
var contact = (from a in db.Contacts where a.ContactID == Id select a).FirstOrDefault();
and since you only want 2 properties of Contact, then return an anonymous object containing only those properties (there is no point degrading performance by sending data across the wire which you never use
var data = new { Email1 = contact.Email1, Mobile1 = contact.Mobile1 };
and finally specify the JsonRequestBehavior option since your making a GET call
return Json(data, JsonRequestBehavior.AllowGet;);
Next, your not generating any inputs with id="Email1" and id="Mobile1". Both textboxes you have create bind to ContactID, so I assume these should be
#Html.TextBoxFor(model => model.Email1, new { #class = "form-control" })
#Html.TextBoxFor(model => model.Mobile1, new { #class = "form-control" })
assuming that Email1 and Mobile1 are also properties of the model in the view.
Your textboxes will now be updated in the success callback
Side notes:
Always use url: '#Url.Action(....)', to ensure the correct url is
generated
Use data: { CustomerContactID: $(this).val() },
Change your method parameter to public JsonResult
GetEmailByCustomerContactId(Guid CustomerContactId) and delete the
Guid.Parse (the DefaultModelBinder will do the conversion)
Remove new { type = "text" } from your Html.TextBoxFor() methods
(the helper already adds that)

making a text field read only

I am using the code below to make the text entry read only but this does not become read only any idea why this could be
#Html.EditorFor(model => model.UserName, new { Readonly = "Readonly"})
Why cont you use
#Html.EditorFor(model => model.UserName, new { #readonly = true});
or you can use like
#Html.EditorFor(model => model.UserName, new { #readonly = "readonly"});
try textboxfor
#Html.TextBoxFor(model => model.UserName, new { #readonly = true})
The HtmlHelper EditorFor do not have overloads that take HTML attributes.
Instead of EditorFor go with TextBoxFor
#Html.TextBoxFor(model => model.UserName, new { disabled = "disabled", #readonly = "readonly"})
hope it helps

Categories

Resources