change event not perform on datepicker through jquery - javascript

I want to pass a selected date to controller for performing operation on database.
But my jquery is not functioning properly..
Can anyone help me solve the issue?
here is my View code :
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
here is my jQuery Code..
$("#DT").on("change", function () {
debugger
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});

HTML:
<div class="form-group">
#Html.TextBoxFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
</div>
jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
alert();
$("#DT").on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: "/ProcessWax/DateWiseData?Date=" + selectedValue ,
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});
</script>
Controller:
[HttpPost]
public ActionResult DateWiseData(DateTime Date)
{
}

If you want that select a date from Jquery datepicker and send it to your controller you can simply bind your datepicker to your controller.
HTML :
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
<button type="submit"></button>
}
Controller :
[HttpPost]
public ActionResult Index(YourModel t)
{
var date = t.DT;
//Do whatever you want (ex. save in database)
return View();
}
UPDATE:
Please Try this code:
$( function() {
$( "#DT" ).datepicker()
.on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
}
});
});
} );
As you can see in the code you forgot to put .datepicker() after $("#DT") .

Related

Dropdown list return always default value 0

I have problem. When i didn't search something in dropdown It has got default selected value=0. And its saving my database. If it can send value"NULL" not will save in my database. How can i send default value "NULL"?
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});
Its my codes. How can i change selected value "0"? It should be "NULL" when i sent form
You can choose a null value as below if the selected value is 0.
pccmail = $(this).val()=="0"?null:(this).val();
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val()=="0"?null:(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});

Dropdown search doesn't work on modal in paramquery

I'm using a modal and when I try to use my dropdown search it doesn't work, but it works in a normal page.
How can I make it work in the modal? I should be able to search customer name in dropdown.
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), null, new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
</div>
</div>
$(document).ready(function() {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '',
width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#CustomerID").empty();
$.each(data, function(index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function(evt) {
pccmail = $(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});

Ajax request does not work on a cascading dropdown value change

Hi I have a cascading drop-down and on it's change I have a requirement to populate another field by getting it's value from the database.
unfortunately when I try to populate the drop-down my ajax always responds an error 500. I don't know what is wrong with it.
I am using this tutorial as my guide.
Here is my Javascript
<script>
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { selectedExpertise: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data.function, function (index, data) {
$('#selectedExperience_FunctionID').append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
and here is my HTML
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.ExpertiseID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.ExpertiseID, Model.expertise, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.ExpertiseID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.FunctionID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.FunctionID, Model.function, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.FunctionID, "", new { #class = "text-danger" })
</div>
</div>
Please help me. I am stuck in this functionality for 4 days now.
point me to the right direction.
Thanks!
i think your ajax is not sending any data because of this
data: { selectedExpertise: selectedExpertise }
change it to
data: { 'selectedExpertise': selectedExpertise }
i think there should be a quote around the object name
Firstly , give id to both the dropdownlists,I didnt find selectedExperience_ExpertiseID and check the $.each function result
Also,I have modified bit of html. Kindly try this code. Hope your method GetFunctionByID is working well.I have take table and its column according to my reference db.
<script type="text/javascript">
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "/DropDownList/GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { stateId: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data, function (key, val) {
$('#selectedExperience_FunctionID').append('<option value="' + val.value + '">' + val.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
#model WebApplication6.Models.StudentModel
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<div class="form-group">
#Html.Label("Expertise", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateNames, Model.StateNames, new { #class = "form-control", #id = "selectedExperience_ExpertiseID" })
#Html.ValidationMessageFor(model => model.StateNames, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Function", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DistrictNames, new List<SelectListItem>(), new { #class = "form-control", #id = "selectedExperience_FunctionID" })
#Html.ValidationMessageFor(model => model.DistrictNames, "", new { #class = "text-danger" })
</div>
</div>

Create registration form with file upload(image) send from ajax to server side (C#) [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 7 years ago.
I used ajax request and included upload file(image) inside the form..
Here is my code:
HTML:
#model acgs_qm.Models.StudentsData
#using (Html.BeginForm("RegisterStudent", "Admin", FormMethod.Post, new { id = "frmrs", enctype = "multipart/form-data" })){
<div id="ruCont">
<div class="first-inline">
<input type="file" id="si_image" name="si_image" accept="image/*" />
<div id="imgHolder"></div>
</div>
<div class="second-inline">
<span>Student ID:</span>
#Html.TextBoxFor(a => a.si_id, new { #class = "user-id-input"})
</div>
<div>
<span>Student Information</span>
<span class="field-name">Full Name:</span>
#Html.TextBoxFor(a => a.si_lname, new { #autocomplete = "off", #placeholder = "Last Name" })
#Html.TextBoxFor(a => a.si_fname, new { #autocomplete = "off", #placeholder = "First Name" })
#Html.TextBoxFor(a => a.si_mname, new { #autocomplete = "off", #placeholder = "Middle Name" })
</div>
<button class="ru-button" form="frmrs">Register Student</button>
</div>
}
JS:
$(document).on("submit", "#frmrs", function (e) {
e.preventDefault();
frm = $(this);
formValidation();
formData = new FormData();
file = document.getElementById("si_image").files[0];
formData.append("si_image", file);
if ($(this).valid()) {
$.ajax({
url: '/admin/registerstudent',
type: 'POST',
data: frm.serialize() + '& si_image=' + formData,
processData: false,
contentType: false,
success: function () {
$.ajax({
url: '/admin/createstudent',
type: 'GET',
success: function () {
alert('Success!')
},
error: function () {
alert('Something went wrong.')
}
});
},
error: function () {
alert('Something went wrong!');
}
});
}
});
Server Side(C#):
[HttpPost]
public ActionResult RegisterStudent(StudentsData sd, HttpPostedFileBase si_image)
{
_ActionModels ma = new _ActionModels();
if (si_image != null)
{
var versions = new Dictionary<string, string>();
var path = Server.MapPath("~/Content/profile-pic/");
versions.Add("_small", "maxwidth=500&maxheight=500&format=jpg");
foreach (var suffix in versions.Keys)
{
si_image.InputStream.Seek(0, SeekOrigin.Begin);
ImageBuilder.Current.Build(
new ImageJob(
si_image.InputStream,
path + si_image.FileName + suffix,
new Instructions(versions[suffix]),
false,
true));
}
}
ma.InsertStudentInfo(sd);
return RedirectToAction("CreateStudent");
}
The problem is that the formdata is returning a null to the controller using the HttpPostedFileBase, I don't know why it returns a null value.
Your response would be very much appreciated, thank you in advance.
Ajax send an object you will need to do somthing like this first
var Data = { Data: frm.serialize() + '& si_image=' + formData }
$.ajax({
url: '/admin/registerstudent',
type: 'POST',
data: Data,
processData: false,
contentType: false,
success: function () {
$.ajax({
url: '/admin/createstudent',
type: 'GET',
success: function () {
alert('Success!')
},
error: function () {
alert('Something went wrong.')
}
});
},
error: function () {
alert('Something went wrong!');
}
});

JQuery ui autocomplete in a MVC partial view only works once

I've been trying to get autocomplete to work for my partial view using JQuery ui. The partial view is updated using AJAX.
The problem is that the autocomplete only works up until the point where the partial view is updated.
This is my partial view
<div id="tagList">
#using (Ajax.BeginForm("AddToTagList", new { urlLocation = Model.UrlLocation }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "tagList" }))
{
if (Model.TagList != null)
{
<div class="form-group">
#Html.LabelFor(model => model.Tag.Text, "Tags", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-xs-10">
<div class="input-group" style="max-width: 300px;">
#Html.EditorFor(model => model.Tag.Text, new { htmlAttributes = new { #class = "form-control", #id = "search_term" } })
#Html.ValidationMessageFor(model => model.Tag.Text, "", new { #class = "text-danger" })
<div class="input-group-btn">
<button type="submit" value="Add Tag" class="btn btn-default">+</button>
</div>
</div>
</div>
</div>
}
}
</div>
This is my JavaScript
$(document).ready(function () {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
and this is my autocomplete search action
public JsonResult SearchAutoComplete(string term)
{
using (IDocumentSession session = RavenDbConfig.RavenDBDocumentStore.OpenSession())
{
var results = session.Query<Tag>().Where(x => x.Text.StartsWith(term)).ToList();
return Json(results,JsonRequestBehavior.AllowGet);
}
}
So, my question is, how can i make this work even after the partial view has been updated once?
Your problem is when you reload your PartialView you basicaly delete some part of DOM in your html document and create new one. And all your bindings that you add in $(document).ready() event will be lost.
One of the posible solutions for this problem is to place your autocomplete init code in addition to .ready() event in jquery .ajaxSuccess() global event becouse you reload your PartialViews via Ajax. Like this:
$(document).ajaxSuccess(function() {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
That way you will init your autocomplete every time you reload PartialView.

Categories

Resources