I am building an MVC4 app and in my model I have these fields:
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime mDateCreated { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mDateModified { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mDateLastDisplayed { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime mStartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mEndDate { get; set; }
I am trying to set datepickers in a view. Here's what I have done so far:
<div class="float-left">
<p>Date Created:</p>
<p>Date of last modification:</p>
<p>Date Last Displayed:</p>
<p>Date of promotion's start:</p>
<p>Date of promotion's end:</p>
</div>
<div class="float-right">
<p>
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#value = Model.mCardOfTheDay.mDateCreated,
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated"
})
</p>
<p>
#(Model.mCardOfTheDay.mDateModified != null ? Html.DisplayFor(_item => _item.mCardOfTheDay.mDateModified) : Html.Label(ValueDomain.FIELD_UNAVAILABLE))
</p>
<p>#(Model.mCardOfTheDay.mDateLastDisplayed != null ? Html.DisplayFor(_item => _item.mCardOfTheDay.mDateLastDisplayed) : Html.Label(ValueDomain.FIELD_UNAVAILABLE))</p>
<p>
#*#Html.EditorFor(_item => _item.mCardOfTheDay.mStartDate, new { #class = "datePick", #type="date" })*#
#*#Html.TextBoxFor(_item => _item.mCardOfTheDay.mStartDate, new {#id = "dateStart"})*#
#* #Html.TextBoxFor(_item => _item.mCardOfTheDay.mStartDate, new
{
#value = (DateTime?) Model.mCardOfTheDay.mStartDate,
#selectedDate = (DateTime?) Model.mCardOfTheDay.mStartDate,
#class = "datePick",
#type = "date",
#id = "dateStart"
})*#
</p>
<p>
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mEndDate, new
{
#value = Model.mCardOfTheDay.mEndDate,
#selectedDate = Model.mCardOfTheDay.mEndDate,
#class = "datePick",
#type = "date",
#id = "dateEnd"
})
</p>
</div>
<div class="clear"></div>
And CSS to show what I'm doing with the classes:
$('.datePick').datepicker({
dateFormat: "dd/ww/yy",
});
$('.datePick').each(function () {
var a = $(this).datepicker({
dateFormat: "dd/ww/yy",
defaultDate: new Date($(this).val())
});
});
This shows the various problems I have. First:
Using Html.TexborFor helpers with #value, #selectedDate and so on does displays a datepicker, but this datepicker's default shown value is aaaa-mm-dd instead of the value binded to the model and when I pass the model to the controller none of the data is kept (meaning that the mEndDate is always null);
Trying only to set a datepicker ends up with the same results;
Here's a sample of Html code behind to show you the "results" I have: <input class="input-validation-error datePick" data-val="true" data-val-date="The field mDateCreated must be a date." data-val-required="The mDateCreated field is required." id="dateCreated" name="mCardOfTheDay.mDateCreated" selectedDate="11/21/2013 00:00:00" type="date" value="" />
And if I use the EditorFor, all I have is a date in string format, no datepicker.
What I want is a datepicker with the proper date selected that passed the selected date to the controller method in post. Can anyone help me figure out why this does not work?
You shouldn't be overriding the value of the date input with the same date in a different format, there is no reason to and it will only cause headaches. From my experience you're better off leaving it as is.
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated"
})
What you need to do however is configure the datepicker properly so that it knows how to interpret the date coming from your database. If you want to show a different format to the user than the one posted back to the server, you can make use of the altField (source) and altFormat (source) option.
That will allow you to use dateFormat to display the date in whichever format you like in the input to the user, while keeping the posted value in the right format.
You won't need this anymore :
$('.datePick').each(function () {
var a = $(this).datepicker({
dateFormat: "dd/ww/yy",
defaultDate: new Date($(this).val())
});
});
You'll also need to get rid of ApplyFormatInEditMode = true on your model property attributes. Let the framework handle dates based on current culture, don't try working against it by applying formats all over the place.
Just leave the textbox value be whatever your database sends, and use the datapicker's functionality to do what you need on the client side.
The only time I would advise overriding the value is if you're worried about the input showing the time part when you only want the date. In that case, you should do it like so :
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated",
#Value = Model.mCardOfTheDay.mDateCreated.ToString("mm/d/yyyy")
})
Notice #Value with a capital v, that is actually important and not a typo. You then pass a date format to the ToString method, but it needs to be the same format as your database.
Edit:
I went ahead and built a small test-case to try and replicate your issue. Here's what I have :
Controller :
public ActionResult Test()
{
return View(new TestViewModel()
{
DateCreated = DateTime.Now.AddDays(10)
});
}
[HttpPost]
public ActionResult Test(TestViewModel model)
{
return RedirectToAction("Test");
}
ViewModel :
public class TestViewModel
{
public DateTime DateCreated { get; set; }
}
View :
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.DateCreated, new {
#type = "date",
#Value = Model.DateCreated.ToString("d")
})
<input type="submit">
}
// This is the rendered input
<input Value="12/1/2013" data-val="true" data-val-date="The field DateCreated must be a date." id="DateCreated" name="DateCreated" type="date" value="12/1/2013 4:03:19 PM" />
JS:
$('input[type="date"]').datepicker();
This all works as expected; datepicker has the date in the input's value selected by default, value of model.DateCreated is set to a DateTime object on post. Notice I haven't messed with formats anywhere but in the display value where I replaced the full date with the standard short date pattern.
Can you try simplifying your code to match what I have and let me know what happens?
Well, after so many years you would definitely have sorted out this issue but still wanted to answer for all those who are new to this problem:
The datepicker should take the format YYYY-MM-DD as its value. Single digit days and months should be padded with a 0. January is 01. You can simply modify your date format as
#Value = Model.DateCreated.ToString("yyyy-MM-dd")
Related
I am unable to find a solution for this as I think this is a bug, or maybe I am not seeing something I should have.
I am passing a model from controlled to view as strongly typed data. However, only one parameter is bugged, it clears it's data after post-back.
When I click Search..
You can see here, the date from Closed Time is still there, but the text from Cut Off time has gone. The date you see at the end is the value of #Model.CutOffTimeFrom - #Model.CutOffTimeTo just to see if the data was cleared or deleted, but it's not, it's just the display on the EditorFor was removed.
I also tried this one, using <input> tag but it's still the same output.
Below is my model:
[AssertThat("CutOffTimeFrom <= CutOffTimeTo", ErrorMessage = "Date To should be greater than Date From")]
[RequiredIf("CutOffTimeFrom != null", ErrorMessage = "Date From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeFrom { get; set; }
[RequiredIf("CutOffTimeTo != null", ErrorMessage = "Cut Off Time From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeTo { get; set; }
and here is the view:
<div>
#*<input type="date" name="CutOffTimeFrom" value="#Model.CutOffTimeFrom" class="form-control input-sm" />-<input type="date" name="CutOffTimeTo" value="#Model.CutOffTimeTo" class="form-control input-sm" />*#
#Html.EditorFor(m => m.CutOffTimeFrom, new { htmlAttributes = new { #class = "form-control input-sm" } }) - #Html.EditorFor(m => m.CutOffTimeTo, new { htmlAttributes = new { #class = "form-control input-sm" } })
#Html.ValidationMessageFor(model => model.CutOffTimeFrom, "", new { #class = "text-danger" })
#Html.ValidationMessageFor(model => model.CutOffTimeTo, "", new { #class = "text-danger" })
</div>
All other fields works just fine. Only Cut Off time is being cleared, although it satisfies the search criteria, value is still passed on the model, but it's just not displayed on the view.
Anyone encountered this issue?
Can we see the Controller handling this, because it might happen that its not model binding
I thoroughly checked the differences of each element, property, parameter and saw one difference, the date format. Saw the bug upon checking inspect element of each EditorFor and saw they were different dates, 2019/02/08 and 02/08/2019, where the latter is wrong.
Changed it from:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
To:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Probably the [DataType(DataType.Date)] is unable to render 02/08/2019 that's why it doesn't repopulate the form.
How would I generate a select list, where the text field, is made up of two or more text columns, eg: Where I have a Description and Rate field in my database, I want to combine these to show:
Large--£200
Medium--£150
Small--£100
Controller code is:
var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");
...and my view is (currently):
<div class="editor-field">
#Html.DropDownList("StandID", "--Select--")
</div>
...but the "Description" + "-- £" + "Rate"); won't run:
DataBinding:
'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4'
does not contain a property with the name 'Description--£Rate'.
Thanks for any help,
Mark
You could create a new anonymous class using a simple LINQ projection, and then use the SelectList(IEnumerable, string, string) constructor overload to specify the value and text fields to be used for the <option> elements i.e.:
var stands =
db.Stands
.Where(s => s.ExhibitorID == null)
.Select(s => new
{
StandID = s.StandID,
Description = string.Format("{0}-- £{1}", s.Description, s.Rate)
})
.ToList();
ViewBag.StandID = new SelectList(stands, "StandID", "Description")
Edit
In C#6 and later, string interpolation makes for better reading than string.Format
...
Description = $"{s.Description}-- £{s.Rate}"
If you project to a strong ViewModel class name (instead of to an anonymous class), you will undoubtedly want to replace the magic strings with the safety of the nameof operator:
ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
IEnumerable<SelectListItem> selectList = from s in stands
select new SelectListItem
{
Value = s.StandID,
Text = s.Description + "-- £" + s.Rate.ToString()
};
ViewBag.StandID = new SelectList(selectList, "Value", "Text");
You can create a partial Model class
public partial class Stand
{
public string DisplayName
{
get
{
return this.Description + "-- £" + this.Rate.ToString();
}
}
}
Then in your View
var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
ViewBag.StandID = new SelectList(stands,"StandID", "DisplayName");
The Format of the constructor that you are using is
SelectList(IEnumerable items, string dataValueField, string dataTextField).
So when you use it the way you have you are actually telling it to bind to the TextField called "Description-- £Rate" and if this is not what the field is called coming in the from the DB it won't know what you are indicating.
Either of the two methods described above will work as long as the value you have in your dataValueField matches the name of the property you put the Value in and the dataTextField matches the property name of where you put the Text, perhaps a mix of the two solutions above. (Only because I prefer lambda expressions over linq.) and using a selectlist item prevents it from have to do a ToList on the collection after the transform. you are actually creating the objects that naturally bind to a select list.
You also may want to put in checks on the description or rate to make sure they aren't empty before putting them into the list
var stands = db.Stands.Where(s => s.ExhibitorID == null)
.Select(s => new SelectListItem
{
Value = s.StandID.ToString(),
Text = s.Description + "-- £" + s.Rate.ToString()
});
ViewBag.StandID = new SelectList(stands, "Value", "Text");
I did this by modifying my View Model, here are my code:
The View Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcEsosNew.Models;
using System.Web.Mvc;
namespace MvcEsosNew.ViewModels
{
public class EntitlementViewModel
{
public int EntitlementCount { get; set; }
public Entitlement Entitlement { get; set; }
public SelectList Member { get; set; }
public SelectList Job_Grade { get; set; }
public SelectList Department { get; set; }
public SelectList Esos_Batch { get; set; }
}
public class department_FullName
{
public int deptID { get; set; }
public string deptCode { get; set; }
public string deptName { get; set; }
public string fullName { get { return deptCode + " - " + deptName; } }
}
}
The Controller
public void getAllDepartment(EntitlementViewModel entitlementVM)
{
var department = from Department in db.Departments.Where(D => D.Status == "ACTIVE").ToList()
select new department_FullName
{
deptID = Department.id,
deptCode = Department.department_code,
deptName = Department.department_name
};
entitlementVM.Department = new SelectList(department, "deptID", "fullName");
}
The View
<div class="form-group row">
<div class="col-sm-2">
#Html.LabelFor(model => model.Entitlement.department_id)
</div>
<div class="col-sm-10">
#Html.DropDownListFor(model => model.Entitlement.department_id, Model.Department, new { #class="form-control" })
#Html.ValidationMessageFor(model => model.Entitlement.department_id)
</div>
</div>
The result:
I have a Date field in my DB and I'm trying to update it to the current Date when I press the submit button on my webpage but it does not update. I believe I'm doing the correct steps but here is my code.
Controller:
public ActionResult TakeInventory(int? AssetNum, string owners, string locationId, string clientId)
{
ViewBag.LocationId = new SelectList(db.Locations, "LocationKey", "LocationName");
ViewBag.ClientId = new SelectList(db.ClientSites, "ClientSiteKey", "ClientSiteName");
var records = from s in db.Assets select s;
if (AssetNum != 0)
{
records = records.Where(c => c.AssetKey == AssetNum);
}
if (!String.IsNullOrEmpty(owners))
{
records = records.Where(x => x.InventoryOwner.Equals(owners));
}
if (!String.IsNullOrEmpty(locationId))
{
int locnum = Convert.ToInt32(locationId);
records = records.Where(x => x.LocationKey == locnum);
}
if (!String.IsNullOrEmpty(clientId))
{
int clinum = Convert.ToInt32(clientId);
records = records.Where(x => x.ClientSiteKey == clinum);
}
else
{
return View(records);
}
return View(records);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
{
if (ModelState.IsValid)
{
db.Entry(asset).State = EntityState.Modified;
asset.InventoryDate = DateTime.Now;
db.Assets.Add(asset);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(asset);
}
View:
#foreach (var items in Model)
{
<p>Last Inventory Date: #Html.DisplayFor(modelItem => items.InventoryDate) </p>
<input type="submit" value="Submit" />
Model:
public partial class Asset
{
public System.DateTime InventoryDate { get; set; }
public Asset()
{
InventoryDate = DateTime.Now;
}
}
You want to retrieve the Asset entity again before updating again.
For example,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
{
if (ModelState.IsValid)
{
var entity = (from s in db.Assets where AssetNum == asset.AssetNum Select s).FirstOrDefalt();
entity.InventoryDate = DateTime.Now;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(asset);
}
Is a bad practice:
asset.InventoryDate = DateTime.Now;
At least, you need:
1. SaveChanges() your DbContext
2. Your DateTime field in backend must be Nullable or NotNull in Db (there is no inmpicit conversion)
But the real trouble is timezones. Its all works fine, if you have only one instance in only one datacenter and all your clients is from only one small and beauty country (one timezone wide)
DateTime.Now returns you local mashine timezone time.
If you use your 'entity.InventoryDate' in any kind of requests query it can return confused rezults, and can be surprized with funny result: for ex., value with tomorrow datetime relatively to you :)
For Web-services always cast to UTC that kind of fields, or use triggers or default expression for this kind of fields inside your DB engine
P.S. Russia is 11 timezones wide, i know what i'm talking about
Why you are passing the Current date , there is no need for that you can you Sql build in function "GETDATE()" to Get the current Date
I have the following view model
public class ProjectVM
{
....
[Display(Name = "Category")]
[Required(ErrorMessage = "Please select a category")]
public int CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
....
}
and the following controller method to create a new Project and assign a Category
public ActionResult Create()
{
ProjectVM model = new ProjectVM
{
CategoryList = new SelectList(db.Categories, "ID", "Name")
}
return View(model);
}
public ActionResult Create(ProjectVM model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Save and redirect
}
and in the view
#model ProjectVM
....
#using (Html.BeginForm())
{
....
#Html.LabelFor(m => m.CategoryID)
#Html.DropDownListFor(m => m.CategoryID, Model.CategoryList, "-Please select-")
#Html.ValidationMessageFor(m => m.CategoryID)
....
<input type="submit" value="Create" />
}
The view displays correctly but when submitting the form, I get the following error message
InvalidOperationException: The ViewData item that has the key 'CategoryID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
The same error occurs using the #Html.DropDownList() method, and if I pass the SelectList using a ViewBag or ViewData.
The error means that the value of CategoryList is null (and as a result the DropDownListFor() method expects that the first parameter is of type IEnumerable<SelectListItem>).
You are not generating an input for each property of each SelectListItem in CategoryList (and nor should you) so no values for the SelectList are posted to the controller method, and therefore the value of model.CategoryList in the POST method is null. If you return the view, you must first reassign the value of CategoryList, just as you did in the GET method.
public ActionResult Create(ProjectVM model)
{
if (!ModelState.IsValid)
{
model.CategoryList = new SelectList(db.Categories, "ID", "Name"); // add this
return View(model);
}
// Save and redirect
}
To explain the inner workings (the source code can be seen here)
Each overload of DropDownList() and DropDownListFor() eventually calls the following method
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata,
string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,
IDictionary<string, object> htmlAttributes)
which checks if the selectList (the second parameter of #Html.DropDownListFor()) is null
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
which in turn calls
private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
which evaluates the the first parameter of #Html.DropDownListFor() (in this case CategoryID)
....
o = htmlHelper.ViewData.Eval(name);
....
IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
if (selectList == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
MvcResources.HtmlHelper_WrongSelectDataType,
name, o.GetType().FullName, "IEnumerable<SelectListItem>"));
}
Because property CategoryID is typeof int, it cannot be cast to IEnumerable<SelectListItem> and the exception is thrown (which is defined in the MvcResources.resx file as)
<data name="HtmlHelper_WrongSelectDataType" xml:space="preserve">
<value>The ViewData item that has the key '{0}' is of type '{1}' but must be of type '{2}'.</value>
</data>
according to stephens (user3559349) answer, this can be useful:
#Html.DropDownListFor(m => m.CategoryID, Model.CategoryList ?? new List<SelectListItem>(), "-Please select-")
or in ProjectVM:
public class ProjectVM
{
public ProjectVM()
{
CategoryList = new List<SelectListItem>();
}
...
}
Most Likely Caused some sort of error redirecting to your page and you not initializing your model's drop down lists again.
Make sure that you initialize your drop downs in either the model's constructor or every time before you send said model to the page.
Otherwise you will need to maintain the state of the drop down lists either through the view bag or through the hidden value helpers.
OK, the poster's canned answer neatly explained why the error occurred, but not how to get it to work. I'm not sure that's really an answer, but it did point me in the right direction.
I ran into the same issue and found a slick way to resolve it. I'll try to capture that here. Disclaimer - I work on web pages once a year or so and really don't know what I'm doing most of the time. This answer should in no way be considered an "expert" answer, but it does the job with little work...
Given that I have some data object (most likely a Data Transfer Object) that I want to use a drop-down list to supply valid values for a field, like so:
public class MyDataObject
{
public int id;
public string StrValue;
}
Then the ViewModel looks like this:
public class MyDataObjectVM
{
public int id;
public string StrValue;
public List<SectListItem> strValues;
}
The real problem here, as #Stephen so eloquently described above, is the select list isn't populated on the POST method in the controller. So your controller methods would look like this:
// GET
public ActionResult Create()
{
var dataObjectVM = GetNewMyDataObjectVM();
return View(dataObjectVM); // I use T4MVC, don't you?
}
private MyDataObjectVM GetNewMyDataObjectVM(MyDataObjectVM model = null)
{
return new MyDataObjectVM
{
int id = model?.Id ?? 0,
string StrValue = model?.StrValue ?? "",
var strValues = new List<SelectListItem>
{
new SelectListItem {Text = "Select", Value = ""},
new SelectListITem {Text = "Item1", Value = "Item1"},
new SelectListItem {Text = "Item2", Value = "Item2"}
};
};
}
// POST
public ActionResult Create(FormCollection formValues)
{
var dataObject = new MyDataObject();
try
{
UpdateModel(dataObject, formValues);
AddObjectToObjectStore(dataObject);
return RedirectToAction(Actions.Index);
}
catch (Exception ex)
{
// fill in the drop-down list for the view model
var dataObjectVM = GetNewMyDataObjectVM();
ModelState.AddModelError("", ex.Message);
return View(dataObjectVM);
)
}
There you have it. This is NOT working code, I copy/pasted and edited to make it simple, but you get the idea. If the data members in both the original data model and the derived view model have the same name, UpdateModel() does an awesome job of filling in just the right data for you from the FormCollection values.
I'm posting this here so I can find the answer when I inevitably run into this issue again -- hopefully it will help someone else out as well.
I had the same problem, I was getting an invalid ModelState when I tried to post the form. For me, this was caused by setting CategoryId to int, when I changed it to string the ModelState was valid and the Create method worked as expected.
In my case the first ID in my list was zero, once I changed the ID to start from 1, it worked.
My model contains:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
My controller contains:
public ActionResult Index(int? personId)
{
var people = db.People; // all people in my database
ViewBag.People = new SelectList(people, "Id", "Name", personId);
return View();
}
My view contains:
#using (Html.BeginForm(null, null, FormMethod.Get, new { #class = "form-inline" }))
{
#Html.DropDownList("personId", ViewBag.People as SelectList, "All people", new { #class = "form-control select-submit" })
}
And I have this piece of Javascript:
<script type="text/javascript">
(function ($) {
$(".select-submit").change(function () {
$(this).parents("form").submit();
alert("form submitted!");
});
})(jQuery);
</script>
When I select a person from the DropDownList, I see the alert popup, and the page refreshes. When I select the default option ("All People"), I also see the popup, but the page does not refresh.
I want "personId" to be set to "" on selecting the default option. How can I achieve this?
Ah, I found it. After inspecting the html, I noticed the form was using data validation. These html attributes were getting added after selecting a person:
data-val="true" data-val-number="The field Int32 must be a number." data-val-required="The Int32 field is required."
The form couldn't be submitted because "" is not valid for an Int32. Adding this html attribute to the DropDownList solved it:
data_val = false