I have 3 dropdownlists: Country, State and City. On change of Country dropdown, state dropdown has to populate for selected country, on change of state dropdown, city dropdown has to populate for selected state.
The fuctionality works when the dropdown values are changed from the UI. Now I want to populate the dropdowns with the selected values stored in the database. ie. If my database has values countryId=1, stateId=5, cityId=2 then my dropdown should populate accordingly. For which the dropdown onchanhge has to call directly when selected value is set to it. But the value is getting set for the first dropdown (country dropdown) but state and city does not set the values as country on change is not triggered.
Here is my code:
.cshtml
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label>Country</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { #class = "form-control show-tick"} )
</div><label id="CountryListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>State</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<select id="ddState" class="form-control show-tick">
<option>-- Please select --</option>
</select>
</div>
<label id="StateListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>City</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<select id="ddCity" name="ddCity" class="form-control show-tick">
<option value="0">-- Please select --</option>
</select>
</div>
<label id="CityListLable" style="color:red;"></label>
</div>
</div>
</div>
Jquery:
$('#CountryId').change(function () {
//alert($(this));
var cN;
var UserType = $(this).data('type');
$('#ddState').selectpicker();
$('#ddState').empty();
$('#ddState').selectpicker('refresh');
$('#ddState').append("<option>-- Please select --</option>");
cN = $('#CountryId').val();
if (cN === '') {
return false;
} else {
$.ajax({
url: "/AdminUser/GetStatesForCountry?countryId=" + cN, success: function (result) {
console.log(result);
$.each(result, function (key, value) {
$('#ddState')
.append($("<option></option>")
.attr("value", value.stateId)
.text(value.stateName));
$('#ddState').selectpicker('refresh');
$('#ddState').selectpicker('val', "-- Please select --");
});
}
});
}
});
$('#ddState').change(function () {
var UserType = $(this).data('type');
$('#ddCity').selectpicker();
$('#ddCity').empty();
$('#ddCity').selectpicker('refresh');
$('#ddCity').append("<option>-- Please select --</option>");
cN = $('#ddState').val();
if (cN === '') {
return false;
} else {
$.ajax({
url: "/AdminUser/GetCitiesForState?StateId=" + cN, success: function (result) {
console.log(result);
$.each(result, function (key, value) {
$('#ddCity')
.append($("<option></option>")
.attr("value", value.cityId)
.text(value.cityName));
$('#ddCity').selectpicker('refresh');
$('#ddCity').selectpicker('val', "-- Please select --");
});
}
});
}
});
Controller code
var countryData = new List<CountryData>();
IEnumerable<SelectListItem> countryList = new List<SelectListItem>();
countryData = (List<CountryData>)HttpContext.Cache.Get("countryResponse");
if (countryData == null)
{
string response = Service.APIHelper_GET(StringConstants.GetCountryDetails);
if (!response.Equals("Internal Server Error."))
{
countryData = new JavaScriptSerializer().Deserialize<List<CountryData>>(response);
HttpContext.Cache.Insert("countryResponse", countryData);
}
}
countryList = countryData.Select(m => new SelectListItem() { Text = m.countryName, Value = m.countryId.ToString() });
ViewBag.country = countryList;//new SelectList(countryList);
public JsonResult GetStatesForCountry(int countryId)//get states for countryid = id
{
Session["CountryId"] = countryId;
return Json(getStateList(countryId), JsonRequestBehavior.AllowGet);
}
public List<State> getStateList(int countryId)
{
var stateList = new List<State>();
stateList = (List<State>)HttpContext.Cache.Get("StateResponseForCountry_" + countryId);
if (stateList == null)
{
var response = (List<CountryData>)HttpContext.Cache.Get("countryResponse"); //this wont b null bcz on page load putting country list to chache
foreach (var item in response)
{
if (item.countryId == countryId)
{
stateList = item.states;
}
}
HttpContext.Cache.Insert("StateResponseForCountry_" + countryId, stateList);
}
return stateList;
}
public JsonResult GetCitiesForState(int StateId)
{
var cityList = new List<City>();
cityList = (List<City>)HttpContext.Cache.Get("CityResponseForState_" + StateId);
if (cityList == null)
{
List<State> stateList = getStateList(Convert.ToInt32(Session["CountryId"]));
foreach (var item in stateList)
{
if (item.stateId == StateId)
{
cityList = item.cities;
}
}
HttpContext.Cache.Insert("CityResponseForState_" + StateId, cityList);
}
return Json(cityList, JsonRequestBehavior.AllowGet);
}
Here is the scenario for better understanding of my issue:
I have a create user page in which user will select from cascaded dropdowns (country, state, city) and save selected valued to database. The problem is in edit user, where I need to populate the dropdowns based on selected values. ie. I need to populate state dropdown with selected values from database.
UPDATE
With the help of #Sagar's solution I have managed to set selected value for the country dropdown. But the state and city dropdowns are still not getting set. Here is the updated code:
cshtml
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label>Country</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { #class = "form-control show-tick" })
</div><label id="CountryListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>State</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { #class = "form-control show-tick" })
</div>
<label id="StateListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>City</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.fKCityId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { #class = "form-control show-tick" })
</div>
<label id="CityListLable" style="color:red;"></label>
</div>
</div>
</div>
Jquery
$(document).ready(function () {
var countryId = $('#CountryId').val();
getStates(countryId);
var StateId = $('#StateId').val();
alert(StateId);/// here I am not getting correct value -- it passes stateId='-- Please select --'
getCities(StateId);
$('#CountryId').change(function () {
var countryId = $(this).val();
getStates(countryId);
});
$('#StateId').change(function () {
var StateId = $(this).val();
getCities(StateId);
});
});
function getStates(countryId) {
$('#StateId').selectpicker();
$('#StateId').empty();
$('#StateId').selectpicker('refresh');
$('#StateId').append("<option>-- Please select --</option>");
if (countryId === '') {
return false;
} else {
$.ajax({
url: "/AdminUser/GetStatesForCountry?countryId=" + countryId, success: function (result) {
console.log(result);
$.each(result, function (key, value) {
$('#StateId')
.append($("<option></option>")
.attr("value", value.stateId)
.text(value.stateName));
$('#StateId').selectpicker('refresh');
$('#StateId').selectpicker('val', "-- Please select --");
});
}
});
}
}
function getCities(stateId)
{
$('#fKCityId').selectpicker();
$('#fKCityId').empty();
$('#fKCityId').selectpicker('refresh');
$('#fKCityId').append("<option>-- Please select --</option>");
if (stateId === '') {
return false;
} else {
$.ajax({
url: "/AdminUser/GetCitiesForState?StateId=" + stateId, success: function (result) {
console.log(result);
$.each(result, function (key, value) {
$('#fKCityId')
.append($("<option></option>")
.attr("value", value.cityId)
.text(value.cityName));
$('#fKCityId').selectpicker('refresh');
$('#fKCityId').selectpicker('val', "-- Please select --");
});
}
});
}
}
You have to call the ajax on change as well as document ready then it will work fine:
Like:
Create Some common function to call it on both ready and change state:
function getCountryStates(countryId){
//your ajax to get states by country
}
$(document').ready(function () {
var countryId = $('#CountryId').val();
getCountryStates(countryId);
});
$('#CountryId').change(function () {
var countryId = $(this).val();
getCountryStates(countryId);
});
You have to follow the above same process to get cities of selected state.
This will work.
I have managed to solve the issue with the help of #StephenMuecke comments.
All I had to do was, to populate the dropdowns while passing the model to the view.
Code:
Model usersDetail = users.userDetail;
ViewBag.State = getStateList(usersDetail.CountryId).Select(m => new SelectListItem() { Text = m.StateName, Value = m.Id.ToString() });
ViewBag.City = getCityList(usersDetail.StateId).Select(m => new SelectListItem() { Text = m.CityName, Value = m.Id.ToString() });
return View(usersDetail);
and modified .cshtml to populate state and city from viewbag:
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label>Country</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { #class = "form-control show-tick" })
</div><label id="CountryListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>State</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.StateId, (IEnumerable<SelectListItem>)ViewBag.State, "-- Please select --", new { #class = "form-control show-tick" })
#*<select id="State" class="form-control show-tick">
<option>-- Please select --</option>
</select>*#
</div>
<label id="StateListLable" style="color:red;"></label>
</div>
</div>
<div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
<label>City</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
#Html.DropDownListFor(m => m.fKCityId, (IEnumerable<SelectListItem>)ViewBag.City, "-- Please select --", new { #class = "form-control show-tick" })
#*<select id="ddCity" name="ddCity" class="form-control show-tick">
<option value="0">-- Please select --</option>
</select>*#
</div>
<label id="CityListLable" style="color:red;"></label>
</div>
</div>
</div>
Related
I am using two viewbags to get the same list(List of tags) on get request these viewbags are showing list as a dropdown but when I submit the page (post request) they are binding the 0 values(no matter what I select from the dropdown list) with the object in the controller but when I used only the single dropdown list it binding its value with an object in the controller?
[HttpGet]
public ActionResult CreateNewTotalizerTag()
{
//This is RawTag List
var RawTaglist1 = cRTu.RawTagsList();
ViewBag.RawTaglist1 = new SelectList(RawTaglist1, "Real_Tag_Id", "R_Tag_Name");
//This is RawTag List
var RawTaglist2 = cRTu.RawTagsList();
ViewBag.RawTaglist2 = new SelectList(RawTaglist2, "Real_Tag_Id", "R_Tag_Name");
return View();
}
//Controller
[HttpPost]
public ActionResult CreateNewTotalizerTag(RawTagVM rawTagVM)
{
return View(rawTagVM);
}
#using (Html.BeginForm("CreateNewTotalizerTag", "TotalizerTags", FormMethod.Post))
{
#Html.HiddenFor(x=>x.Real_Tag_Id)
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<!-- general form elements disabled -->
<div class="card card-warning">
<div class="card-header" style="background-color:#343a40">
<h3 class="card-title" style="color:white">Create Totalizer Tag</h3>
</div>
<!-- This form is to create Raw tag totalizer onPrem or onCloud -->
<div class="card-body">
<form role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<div class="custom-control custom-switch">
#Html.CheckBoxFor(m => m.Is_Cloud_Totalizer, new { #class = "custom-control-input", id = "Is_Cloud_Totalizer" })
<label class="custom-control-label" for="Is_Cloud_Totalizer">Is Cloud Totalizer?</label>
</div>
</div>
</div>
</div>
<!-- On Cloud Inputs starts here -->
<div id="oncloud_totalizer" style="display:none">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Enter Tag Name</label>
#Html.EditorFor(m => m.R_Tag_Name, new { htmlAttributes = new { #class = "form-control" } })
#*#Html.ValidationMessageFor(model => model.R_Tag_Name, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Select Raw Tag</label>
#Html.DropDownListFor(m => m.Real_Tag_Id_Cloud, (IEnumerable<SelectListItem>)ViewBag.RawTaglist1, "Select Raw Tag", new { #class = "form-control", id = "Raw_Tag_List1" })
</div>
</div>
</div>
</div>
<!-- On Prem Inputs starts here -->
<div class="row" id="onPrem_totalizer">
<div class="col-sm-6">
<div class="form-group">
<label>Select Raw Tag</label>
#Html.DropDownListFor(m => m.Real_Tag_Id, (IEnumerable<SelectListItem>)ViewBag.RawTaglist2, "Select Raw Tag", new { #class = "form-control", id = "Raw_Tag_List2" })
</div>
</div>
</div>
<div class="form-group">
<center><button type="submit" class="btn btn-primary">Create Totalizer</button></center>
</div>
</form>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
<!-- general form elements disabled -->
<!-- /.card -->
</div>
</div>
</div>
}
<script>
$(document).ready(function () {
// Initialize select2
//$("#Raw_Tag_List1").select2();
//$("#Raw_Tag_List2").select2();
//$("#Source_Tag_List").select2();
$("#Is_Cloud_Totalizer").change(function () {
if (this.checked) {
$("#oncloud_totalizer").show();
$("#onPrem_totalizer").hide();
}
else {
$("#onPrem_totalizer").show();
$("#oncloud_totalizer").hide();
}
});
});
</script>
You could assign the viewbag properties on postback aswell. Viewbag properies are used in the view (cshtml) for rendering the page, the resulting rendered HTML page that is sent to the client does not know them, and also they are not sent back to the server together with form data on post back.
//Controller
[HttpPost]
public ActionResult CreateNewTotalizerTag(RawTagVM rawTagVM)
{
var RawTaglist1 = cRTu.RawTagsList();
ViewBag.RawTaglist1 = new SelectList(RawTaglist1, "Real_Tag_Id", "R_Tag_Name");
//This is RawTag List
var RawTaglist2 = cRTu.RawTagsList();
ViewBag.RawTaglist2 = new SelectList(RawTaglist2, "Real_Tag_Id", "R_Tag_Name");
return View(rawTagVM);
}
You might try to assign the drop down a list of SelectListItem
ViewBag.RawTaglist1 = RawTaglist1.Select(x => new SelectListItem()
{
Value = x.Real_Tag_Id.ToString(),
Text = x.R_Tag_Name
}).ToList();
I'm trying to submit my form using Ajax.beginform. I tried everything but i am getting this resource cannot found error.
I have two models - PatientEligibility and PatientDetails. Both contains 10-12 properties respectively.
I have created on viewmodel using those two models and I am trying to use some of the properties in one partial view and submitting that data button click
my view -
#model Portal.Models.EligibilityViewModel
<script type="text/javascript">
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function () {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
});
</script>
<div class="row margin-top-0">
<div class="col-xs-12 col-sm-12">
<h4><b>Patient Eligibility</b></h4>
</div>
</div>
#using (Ajax.BeginForm("SubmitPatientEligibility", "Ophthalmic", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsAboveSixty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbvSixty", #class = "form-control", Name = "group1[]" } })
The patient is 60 or over
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBelowSixteen, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbUnderSixteen", #class = "form-control", Name = "group1[]" } })
The patient is under 16
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBetweenForty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbovenForty", #class = "form-control", Name = "group1[]" } })
The patient is 40 or over and is the parent/brother/sister/child of a person who has or has had gloucoma
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsStudent, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbStudent", #class = "form-control", Name = "group1[]" } })
The patient is full time student aged 16, 17 or 18 at the establishment below.
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsPrisoner, new { data_toggle = "collapse", data_target = "#dvseenNotseen", htmlAttributes = new { id = "cbPrisoner", #class = "form-control" } })
The patient is prisoner on leave from the prison detailed below
</label>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
#Html.LabelFor(p => p.PatientBenefit.NINNumber)
#Html.EditorFor(model => model.PatientBenefit.NINNumber, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<label>DATE OF BIRTH</label>
#Html.TextBoxFor(model => model.PatientBenefit.DOB, new { #class = "form-control", autocomplete = "off", #id = "datetimepicker1" })
</div>
</div>
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-3">
<button class="btn btn-default" name="btnBack">Previous</button>
</div>
<div class="col-xs-12 col-sm-9 text-right">
<button class="btn btn-default" name="btnBack">Save Draft</button>
<button class="btn btn-success fa fa-chevron-right icon-right" name="btnNext" type="submit">Next</button>
</div>
</div>
}
and my model is like this -
public class EligibilityViewModel
{
public PatientEligibility PatientEligibility { get; set; }
public PatientBenefit PatientBenefit { get; set; }
}
I am trying to call this method on submit of Next button -
public class OphthalmicController : Controller
{
[HttpPost]
public ActionResult SubmitPatientEligibility(EligibilityViewModel model)
{
return null;
}
}
i dont know why but i am getting this 500 error resource cannot found for this method.
What am I missing here?
Im using a bootstrap datetimepicker to input appointment datetimes to a knockout viewmodel. the viewmodel has an object appointment which holds the observable values for all appointment object. Im sending the appointment to the controller via an ajax call, however after many null values for my dates i found that you must create a custom binding for the datepicker. after implementing the custom binding on the git page of the datepicker i am still receiving null values for both the start and end dates.
Have i implemented the custom binding incorrectly?
Code:
View:
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='startdatepicker'>
<input type='text' class="form-control" data-bind="date: appointment.start, format: 'DD MMM YYYY'" /><span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='enddatepicker'>
<input type='text' class="form-control" data-bind="date: appointment.end, format: 'DD MMM YYYY'" /><span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
Scripts section at bottom of view
#section Scripts {
#Scripts.Render("~/bundles/jqueryval",
"/Scripts/ViewModels/AppointmentFormViewModel.js")
<script>
$(function () {
$('#startdatepicker').datetimepicker();
$('#enddatepicker').datetimepicker();
});
var viewModel = new AppointmentFormViewModel(#Html.HtmlConvertToJson(Model));
ko.applyBindings(viewModel);
</script>
}
Knockout viewmodel
function AppointmentFormViewModel(appointment) {
var self = this;
self.saveCompleted = ko.observable(false);
self.sending = ko.observable(false);
self.isCreating = appointment.id == 0;
self.appointment = {
id: appointment.id,
start: ko.observable(appointment.start),
end: ko.observable(appointment.end),
text: ko.observable(appointment.text),
clientid: ko.observable(appointment.clientid),
employeeid: ko.observable(appointment.employeeid),
roomid: ko.observable(appointment.roomid),
};
ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
ko.utils.registerEventHandler(element, 'change', function () {
var value = valueAccessor();
if (element.value !== null && element.value !== undefined && element.value.length > 0) {
value(element.value);
}
else {
value('');
}
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var pattern = allBindings.format || 'DD/MM/YYYY';
var output = "-";
if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) {
output = moment(valueUnwrapped).format(pattern);
}
if ($(element).is("input") === true) {
$(element).val(output);
} else {
$(element).text(output);
}
}
};
here is the appointment model object that was sent from the knockout viewmodel
as you can see the date time is not what was selected
Here is how it posted to server
is creating is a variable to determine whether the form is editing or creating an appointment
self.appointment.__RequestVerificationToken = form[0].value;
$.ajax({
url: (self.isCreating) ? 'Create' : 'Edit',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: ko.toJS(self.appointment)
})
I am validating date input server side and adding ModelError if user input is invalid. Following is my code
public ActionResult EditOffer()
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var objOffer = context.tbl_offer.Where(x => x.LNG_OFFER_ID == offerID).FirstOrDefault();
ViewBag.OfferID = offerID;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
if (System.IO.File.Exists(Server.MapPath(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID))))
{
objOffer.TXT_OFFER_SMALL_PATH = string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID);
}
return View("AddOffer", objOffer);
}
}
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return RedirectToAction("EditOffer");
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
return RedirectToAction("EditOffer");
}
View
<div class="panel-body container-fluid">
#using (Html.BeginForm("EditOffer", "Store", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" , id="offerForm"}))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true);
<div class="form-group">
<label class="col-sm-3 control-label">Offer Title</label>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.TXT_OFFER_TITLE, new { #class = "form-control", placeholder = "Offer Title", autocomplete = "off", name = "title" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TITLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Banner</label>
<div class="col-sm-9">
<div class="image-container" style=" border: 1px solid #ccc; display: table;position:relative">
<a href="#editimage" data-toggle="modal" class="btn btn-sm btn-icon btn-inverse btn-round btn-image-edit" data-toggle="tooltip" data-original-title="Edit">
<i class="icon wb-pencil" aria-hidden="true"></i>
</a>
<div class="img-preview preview-lg">
<img id="image_upload_preview" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="width:100%" alt="your image" />
</div>
</div>
<div class="input-group-file" style="margin-top:5px">
#Html.TextBoxFor(modal => modal.TXT_OFFER_SMALL_PATH, new { #class = "hide", #readonly = "true", width = "0", id = "filePath" })
#Html.ValidationMessageFor(modal => modal.TXT_OFFER_SMALL_PATH, "", new { #class = "text-danger" })
<span class="">
<span class="btn btn-success btn-small btn-file">
Upload Image <i class="icon wb-upload" aria-hidden="true"></i>
<input type="file" name="files" accept="image/*" multiple="" id="fileupload" onchange="showimagepreview(this)">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Detail </label>
<div class="col-sm-6">
#Html.TextAreaFor(model => model.TXT_OFFER_TEXT, new { #class = "form-control", placeholder = "Offer Text", autocomplete = "off", name = "text" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TEXT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Valid For</label>
<div class="col-sm-4">
<div class="input-daterange" data-plugin="datepicker">
<div class="input-group">
<span class="input-group-addon">
<i class="icon wb-calendar" aria-hidden="true"></i>
</span>
#Html.TextBoxFor(model => model.DAT_START_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control from_date", placeholder = "Start Date", autocomplete = "off", name = "start" })
#Html.ValidationMessageFor(model => model.DAT_START_OFFER, "", new { #class = "text-danger" })
</div>
<div class="input-group">
<span class="input-group-addon">to</span>
#Html.TextBoxFor(model => model.DAT_END_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control to_date", placeholder = "End Date", autocomplete = "off", name = "end" })
#Html.ValidationMessageFor(model => model.DAT_END_OFFER, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Is Premium</label>
<div class="col-sm-4">
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 1, new { #id = "ispremiumYes", name = "ispremium", #checked = "checked" })
<label for="ispremiumYes">Yes</label>
</div>
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 0, new { #id = "ispremiumNo", name = "ispremium", })
<label for="ispremiumNo">No</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-3">
<button type="submit" name="#ViewBag.ActionToPerform" class="btn btn-primary">Submit </button>
<button type="reset" class="btn btn-default btn-outline">Reset</button>
</div>
</div>
#Html.Hidden("cropWidth", new { id = "cropWidth" })
#Html.Hidden("cropHeight", new { id = "cropHeight" })
#Html.Hidden("cropPointX", new { id = "cropPointX" })
#Html.Hidden("cropPointY", new { id = "cropPointY" })
#Html.Hidden("ImgSrc", new { id = "ImgSrc" })
}
<div class="modal fade" id="editimage" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document" style="width:1024px;height:768px">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel">Crop the image</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-9">
<div class="cropper text-center">
<img id="image" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="max-width:730px;" alt="Picture">
</div>
</div>
<div class="col-sm-3">
<div class="docs-preview clearfix">
<div class="img-preview preview-lg"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
But Modal Error is not showing on view. What could be the cause ?
When you set your model error then you use RedirectToAction, what mean that you load new page, check in your debug, after that your code go back to GET method and everything is reloaded.
You have to return your View with model.
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available");
if (Edit != null)
{
return View(modal); //if your model is object named modal
}
You didn't see any error because of RedirectToAction. You should use the "View" method. For example you can just write return EditOffer()
If you use return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown. To rectify this error, you should use View() method. like return View(); it return the error to the form data posted page.
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return View(modal);
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
ViewBag.OfferID = Here give the office id;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
ModelState.AddModelError("","Your Error Message"); // Here i am adding Modal Error For Date
return View(modal);
}
}
I have project in which there is a form to edit user details. Initially it is disabled but when user search particular user and click edit button everything is enabled. I capture all changed data except dropdown list newly selected value. when user changed data and submit form. on the server end model property for dropdownlist contains old value in place new changed value.
Please help me
<script>
function Validate(strDecision) {
//alert("Validate");
debugger;
if (strDecision == "EDIT") {
if ($("#MerchDispName").val() == "" || $("#MerchDispName").val() == null) {
$("#DivInfoNErrorMsg").addClass("alert-danger");
$("#DivInfoNErrorMsg").html("<span>There is no data for editing.</span>");
$("#DivInfoNErrorMsg").show();
return false;
}
else {
debugger;
$(".ReadOnly").removeAttr("readOnly", "readOnly");
$(".Disabled").removeAttr("disabled", "disabled");
$("#Update").show();
$("#Edit").hide();
GetDetails();
}
}
else
{
var bFlag = false;
var iLengthPaymentMode = '#Model.dicPaymentModeVal.Count';
var iLengthProgramType = '#Model.dicProgramTypeVal.Count';
var i = 1;
for (; i <= iLengthPaymentMode; ) {
if ($("#PaymentCB" + i).is(":checked")) {
$("#PaymentCB" + i + "hid").val($("#PaymentCB" + i).val());
bFlag = true;
}
i++;
}
if (bFlag == false) {
$("#PaymentCBmsg").html("<span style='color:Red'>*Please select at least one payment option.</span>");
ShowErrorMsg("Please select at least one payment option.");
$("#PaymentCBmsg").show();
return false;
}
for (; i <= iLengthProgramType; ) {
if ($("#ProgramCB" + i).is(":checked")) {
$("#ProgramCB" + i + "hid").val($("#ProgramCB" + i).val());
bFlag = true;
}
i++;
}
if (bFlag == false) {
$("#ProgramCBmsg").html("<span style='color:Red'>*Please select at least one program type.</span>");
ShowErrorMsg("Please select at least one program type.");
$("#ProgramCBmsg").show();
return false;
}
else {
$(".Disabled").attr("disabled", "disabled");
$(".ReadOnly").attr("readOnly", "readOnly");
$("#Edit").show();
$("#Update").hide();
$("#frmMerchantEDIT").submit();
}
}
}
$(document).ready(function () {
//debugger;
var bFlagErrorMessage = '#Model.FlagErrorMessage';
var bFlagInfoMessage = '#Model.FlagInfoMessage';
$('#CountryList').on('change', function () {
debugger;
var id = this.value;
//$("#CountryID").val('0');
$("#CountryID").val(id); // or $(this).val()
});
$('#StateList').on('change', function () {
debugger;
var id = this.value;
//$("#StatesID").val('0');
$("#StatesID").val(id);
alert(id); // or $(this).val()
});
$('#CityList').on('change', function () {
debugger;
var id = this.value;
//$("#CityID").val('0');
$("#CityID").val(id);
//alert(this.value); // or $(this).val()
});
if (bFlagErrorMessage == 'True') {
debugger;
var sErrorMsg = '#Model.ErrorMessage';
$("#DivInfoNErrorMsg").addClass("alert-danger");
$("#DivInfoNErrorMsg").html("<span>" + sErrorMsg + "</span>");
$("#DivInfoNErrorMsg").show();
$(".ReadOnly").removeAttr("readOnly", "readOnly");
$(".Disabled").removeAttr("disabled", "disabled");
$("#Update").show();
$("#Edit").hide();
}
if (bFlagInfoMessage == 'True') {
debugger;
var sErrorMsg = '#Model.InfoMessage';
$("#DivInfoNErrorMsg").addClass("alert-success");
$("#DivInfoNErrorMsg").html("<span>" + sErrorMsg + "</span>");
$("#DivInfoNErrorMsg").show();
}
});
</script>
#using (Html.BeginForm("EDIT_MERCHANT", "MERCHANT_Permission", FormMethod.Post, new { #id = "frmMerchantEDIT", #class = "form-horizontal", #Role = "form" }))
{
#Html.AntiForgeryToken()
//#Html.ValidationSummary()
<div class="logmain_mechant">
<fieldset>
<legend class="panel-heading panel-primary" style="font-size:140%">Edit Merchant</legend>
<div id="DivInfoNErrorMsg" class="alert" hidden="hidden"></div>
<div class="wrapper">
<div class="panel-group" id="accordion">
<div class="panel panel-primary">
<div class="panel-heading">
<a class="accordion-toggle" style="text-decoration:none" data-toggle="collapse"
data-parent="#accordion" href="#collapseOne">
<h2 class="panel-title" style="color:White;font-size:135%">
Personal
<span class="indicator glyphicon glyphicon-chevron-down pull-right"></span>
</h2>
</a>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
<div class="form-group">
<label for="MerchantName" class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Name<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.MerchantName, new { #id = "MerchantName", #class = "form-control ReadOnly",#onclick= "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.MerchantName)
</div>
</div>
<div class="form-group">
<label for="MerchDispName" class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Display Name<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.MerchantDisplayName, new { #id = "MerchDispName", #class = "form-control", #onclick="hideme()",#placeholder="Merchant Display Name" })
#Html.ValidationMessageFor(m => m.MerchantDisplayName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Address1<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address1, new { #id = "Address1", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address1)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col- md-4">Address2:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address2, new { #id = "Address2", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address2)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Address3:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address3, new { #id = "Address3", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address3)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Country<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.CountryID, Model.liCountry, new { #id = "CountryList", #class = "form-control Disabled", #onchange = "GetStates()", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.CountryID, new { #id="CountryId" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.CountryID)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">State<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.StateID, Model.liState, new { #id = "StateList", #class = "form-control Disabled", #onchange = "GetCitis()", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.StateID, new { #id = "StateIds" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.StateName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">City<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.CityID, Model.liCity, new { #id = "CityList", #class = "form-control Disabled", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.CityID, new { #id = "CityIds" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.CityName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">ZipCode<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.ZipCode, new { #id = "ZipCode", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()", #onkeypress = "return validateZipCode(event);" })
#Html.ValidationMessageFor(m => m.ZipCode)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-10 col-sm-6 col-md-4">PG Merchant Name</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#*type="text" name="PayControllerMerName" id="PayControllerMerName" class="form-control" />*#
#Html.TextBoxFor(m => m.sPGMerchantName, new { #id = "PayControllerMerName", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.sPGMerchantName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">PG Merchant ID<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.PayControllerMerID, new { #name = "PayControllerMerID", #id = "PayControllerMerID", #class = "form-control disabled" })
#Html.ValidationMessageFor(m => m.PayControllerMerID)
</div>
</div>
#*<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>*#
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<a class="accordion-toggle" data-toggle="collapse" style="text-decoration:none" data-parent="#accordion" href="#collapseTwo">
<h2 class="panel-title" style="color:White;font-size:135%">
Configuration
<span class="indicator glyphicon glyphicon-chevron-down pull-right"></span>
</h2>
</a>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Website<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.ReturnURL, new { #id = "ReturnURL", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.ReturnURL)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Merchant EmailID<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.EmailID, new { #id = "EmailID", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.EmailID)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Program Type<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#{
var i = 1;
foreach (KeyValuePair<int, string> k in Model.dicProductType)
{
var ProductName = "ProgramCB" + i;
<span class="col-sm-offset-1 pull-left">
<input type="checkbox" name="ProgramCB" value="#k.Key"
checked="#Model.dicProgramTypeVal[k.Key]" id="#ProductName" class="Disabled"
onclick="ProgramClick(#ProductName)" /><label for="#ProductName" style="font-weight:normal;">#k.Value</label> </span>
i = i + 1;
ProductName = ProductName + "hid";
<input type="hidden" id="#ProductName" name="ProgramCB" />
}
}
</div>
<div hidden="hidden" id="ProgramCBmsg"></div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Payment Mode<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#{
i = 1;
foreach (KeyValuePair<int, string> k in Model.dicPaymentMode)
{
var elementName = "PaymentCB" + i;
<input type="checkbox" name="PaymentCB"
value="#k.Key" class="Disabled"
checked="#Model.dicPaymentModeVal[k.Key]"
id="#elementName" onclick="PaymentClick(#elementName)" />
<label for="#elementName"
style="font-weight:lighter;font-size:normal">#k.Value</label>
i = i + 1;
elementName = elementName + "hid";
<input type="hidden" id="#elementName" name="PaymentCB" />
}
}
</div>
#Html.HiddenFor(m => m.CurrentStateID, new { #id="StatesID"})
#Html.HiddenFor(m => m.CurrentCountryID, new { #id = "CountryID" })
#Html.HiddenFor(m => m.CurrentCityID, new { #id = "CityID" })
<div hidden="hidden" id="PaymentCBmsg"></div>
</div>
</div>
</div>
</div>
<div class="panel panel-default" id="Button">
<span style="color:Red">* Required Fields</span>
<div class="col-xs-12 col-sm-10 col-md-8 pull-right">
<button type="button" class="btn btn-default pull-right"
onclick="Validate('UPDATE')" id="Update">Update</button>
<button type="button" class="btn btn-default pull-right"
onclick="Validate('EDIT')" id="Edit">Edit</button>
</div>
</div>
<div hidden="hidden">
<button type="button" class="btn btn-default" id="btnClear" onclick="Clear();" style="display: none;">Clear</button>
</div>
</div>
</div>
</fieldset>
</div>
}
Server side code
if (objMerchant.CurrentCityID != 0 && objMerchant.CurrentCityID != objMerchant.CityID)
objMerchant.CityID = objMerchant.CurrentCityID;
if (objMerchant.CurrentStateID != 0 && objMerchant.CurrentStateID != objMerchant.StateID)
objMerchant.StateID = objMerchant.CurrentStateID;
if (objMerchant.CurrentCountryID != 0 && objMerchant.CurrentCountryID != objMerchant.CountryID)
objMerchant.CountryID = objMerchant.CurrentCountryID;
What i think going wrong is the Hidden control. Your code with dropdownlist contains
#DropDownListFor and #HiddenFor due to which there will be two input with same name and id, and when you are submitting your form. It is taking from the hidden input.
Try to remove the hidden control, because it is not correct to have same id for more than one element in html
I hope this will solve your porblem.