How to assign null/string to an int type in MVC Razor using Entity Framework? - asp.net-mvc-4

I am using a simple MVC 4 application using Entity Framework.
In my View I am displaying data from of a table using webgrid.
View Also has Textboxes(EditorFor) for saving any new record in the table.
I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
Out of 5, two columns are of integer types.
In order to make the textboxes empty initially I am using a new object as -
#if (!dataGrid.HasSelection)
{
Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };
Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel);
}
//------------------------------------------------------------------------
#Html.LabelFor(model => model.DepartmentID)
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
//-----------------------------------------------------------------------------
So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.
So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?

When you use #Html.EditorFor() with a int value, Razor generate a html tag like this
<input type="number" name="propertyName" id="propertyName" value="propertyValue" />
If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.
#Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { #Value = "" } })
Note: It is capital "V", not a lower case "v".

Related

Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year

I am using bootstrap-datetimepicker version 4.17.47 in ASP MVC 4 app.
I have this model property:
public DateTime MonthYear { get; set; }
I assign default value in controller (arbitrary value is just an example actual value is determined through some logic):
model.MonthYear = new DateTime(2017, 3, 1);
I display this in view using datepicker so users can update the value as needed:
#Html.TextBoxFor(model => model.MonthYear, new { #class = "form-control input month-picker" })
Script:
$('.month-picker').datetimepicker({
format: 'MM/YYYY',
useCurrent: false,
toolbarPlacement: 'bottom',
viewMode: 'months'
});
The problem is the control displays "03/0001" instead of "03/2017".
What am I missing here?
Apparently the problem is that the input is being filled with a DD/MM/YYYY date from server when datetimepicker is expecting only MM/YYYY. Try formating the textbox, like:
#Html.TextBoxFor(model => model.MonthYear, "{0:MM/yyyy}", new { #class = "form-control input month-picker" })
That should work.

Display value of datetime in textboxfor at edit time

I am using HTML5 type = "date" and it's working fine.
But when there is type="datetime-local", at the time of editing field it's not displaying using TextBoxFor() in MVC4
This one is working,
#Html.TextBoxFor(c => c.date, "{0:yyyy-MM-dd}", new { #class = "form-control",#placeholder = "DateTime", #type = "date" })
in texbox = "2/15/2015"
but
#Html.TextBoxFor(c => c.datetime, "{0:yyyy-MM-dd HH:mm:ss}", new { #class = "form-control", #placeholder = "OpeningDoor", #type = "datetime-local" })
not displaying data when there is value in "datetime".
textbox = "mm/dd/yyyy _:_:_" instead of "1/15/2015 01:40:00 PM"
The format string needs to be "{0:yyyy-MM-ddTHH:mm:ss}" or you can simply use "{0:s}"
#Html.TextBoxFor(c => c.datetime, "{0:s}", new { #class = "form-control", placeholder = "OpeningDoor", type = "datetime-local" })
Side note: type="date" and type="datetime-local" are only supported in Chrome (a normal textbox will be generated in FireFox and IE) so you should consider using a jquery plugin. Refer browser comparison.

Using a list with MVC radiobuttonfor

I am using radiobuttonfor in MVC 4 and I am trying to give the user a selection of items that he can select. My problem is when one of the items is selected and it's posted to the controller, the string value is a .net system.guid rather than the actual guid value.
#foreach (var person in Model.InterviewDates[i].Interviewers) // all interviewers - not filtered
{
var list = Model.InterviewDates[i].Interviewers.Select(p => p.InterviewerID).ToList();
#Html.Raw(person.InterviewerName + " ")
// TODO: Lambda for getting all Chairs based on interview type and interview date
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair, list, new { #style = "width:auto;background:none;border:none" })
<br />
}
I have a list of people and it contains their user ids. I then want the user to select a radio button to bind that value to the model.
- list Count = 3 System.Collections.Generic.List<System.Guid>
+ [0] {5fb7097c-335c-4d07-b4fd-000004e2d221} System.Guid
+ [1] {5fb7097c-335c-4d07-b4fd-000004e2d222} System.Guid
+ [2] {5fb7097c-335c-4d07-b4fd-000004e2d223} System.Guid
+ Raw View
When I post it goes here:
[HttpPost]
public ActionResult SubmittedInterviews(InterviewManagement InterviewManagement)
{
return View();
}
This is what I can see in quick watch
- InterviewManagement {IMecheAdmin.Models.InterviewManagement} IMecheAdmin.Models.InterviewManagement
+ InterviewDates Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewDate>
- InterviewSchedules Count = 1 System.Collections.Generic.List<IMecheAdmin.Models.InterviewSchedule>
- [0] {IMecheAdmin.Models.InterviewSchedule} IMecheAdmin.Models.InterviewSchedule
Chair "System.Collections.Generic.List`1[System.Guid]" string
Cofacilitator null string
Facilitator null string
+ InterviewDate {01/01/0001 00:00:00} System.DateTime
Location null string
Observer null string
Preference false bool
Site null string
+ Raw View
+ InterviewTypes Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewType>
SelectedMembershipType null string
And this is not what I want:
Chair "System.Collections.Generic.List`1[System.Guid]" string
Doesn't say actual GUID. Any ideas?
Radio button is normally used where we want user to only select only one option from the provided item.
So, you need to pass single object instead of list:
foreach(var item in list)
{
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair,
item.InterviewerID,
new { #style = "width:auto;background:none;border:none" })
}

Select a default value in dropdownlistfor MVC 4

I'm trying to make a dropdownlistfor with a selected value but it doesn't work :/ And I search on the web but I don't find the solution :/
For the moment, I'm doing this :
In C# :
ViewBag.ID_VEH = new SelectList(db.VEHI, "ID_VEH", "COD_VEH", 4); // 4 is an example
In my cshtml :
#Html.DropDownListFor(model => model.ID_VEH, ViewBag.ID_VEH as SelectList)
The dropdownlist is well complete but the default value is not selected :/ do you have an idea please ?
What I like to do is add a list of the items to display in the dropdownlist to my model, so I don't have to pass that list via a viewbag.
Also i like to add a field to my model that contains the SelectedValue, that I fill in the controller
Then you can do
#Html.DropDownListFor(model => model.ID_VEH, new SelectList(Model.listVEH, "ID_VEH", "COD_VEH", Model.SelectedVEH_ID), "--Select VEH--")
just set the initial value of model.ID_VEH to 4:
In the controller:
model.ID_VEH = 4;
Just in case someone has similar problems finding the answer:
I want to have view with the dropdown boxes have focus on the items i give (hardcoded) in the controller:
Controller:
SGLDataRegistration.Models.DataRegistrationModel mdl = rwd.GetData(DateTime.Now.Year, currentWeek, DateTime.Now, 139, 1);
View:
<div id="tempCustomerselect">
#Html.LabelFor(m => m.CustomerName)
#Html.DropDownListFor(m => m.PitchID, new SelectList((new SGLDataRegistration.Models.CustomerModel().GetRoles()).OrderBy(x => x.CustomerName), "PitchID", "CustomerName"), new {id = "ddlCustomer", #class="jsddlCustomer"})
</div>
In this GetData, i setthe desired values hardcoded:
public SGLDataRegistration.Models.DataRegistrationModel GetData(int year, int weekNumber, DateTime datum, int pitchID, int parameter)
{
try
{
DataRegistrationParameters drp = GetParameter(parameter);
//vul een instantie van het dataregistrationmodel
SGLDataRegistration.Models.DataRegistrationModel drm = new Models.DataRegistrationModel();
drm.WeekNumber = weekNumber;
drm.BeginDay = datum;
drm.Parameter = parameter;
drm.Year = year;
drm.PitchID = pitchID;

Remove default 0 from numeric textbox

My model has an EditorFor that binds to a not null numeric field in a database. I wish to keep this field blank so that users can enter or scan numbers into the field. Unfortunately, it defaults to a 0. Is there an easy way to remove the 0 while keeping the field not null?
#Html.EditorFor(model => model.RackNumber, new { id = "RackNumber"})
Change model property type to nullable: public int? RackNumber {get;set;}
You can provide the Value attribute like this:
#Html.EditorFor(model => model.RackNumber, new { Value = Model.RackNumber == 0 ? "" : Model.RackNumber.ToString(), id = "RackNumber"})