I have a partial view being display using modal. The problem that I am having is that I do understand where or when to add the jquery to the modal form that's being called. I understand that the the script is not attached to the modal. How do I do this.
My current code is not working. The autocomplete is not working.
The script is working without using the modal.
In my partial view I have a TextBoxFor with the class using "autocomplete_with_hidden".
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.Ship_To_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(Model => Model.Ship_To_Name, new { #class = "autocomplete_with_hidden", data_url = Url.Action("AutoComplete", "Customer") })
#Html.ValidationMessageFor(model => model.Ship_To_Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
The controller is using the following code.
public ActionResult Autocomplete(string term)
{
var model = db.Customers
.Where(m => term == null || m.Customer_Name.StartsWith(term))
.Take(10)
.Select(m => new
{
label = m.Customer_Name,
Id = m.Ship_To_Code
});
return Json(model, JsonRequestBehavior.AllowGet);
}
Jquery:
$(function () {
$.ajaxSetup({ cache: false, async: true });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
//persist: true,
keyboard: true
}, 'show');
//This is a function
bindForm(this);
});
return false;
});
Jquery Create Auto Complete
var createAutoComplete = function() {
$(this).autocomplete({
minLength: 0,
source: function (request, response) {
var shipto = new Array();
//var url = $(this).attr("data_autocomplete");
var url = $(this.element).data('url');
$.ajax({
async: false,
cache: false,
type: "POST",
url: url,
data: { "term": request.term },
success: function (data) {
for (var i = 0; i < data.length ; i++) {
shipto[i] = { label: data[i].Value, Id: data[i].Key };
}
}
});
response(shipto);
},
select: function (event, ui) {
// fill selected shipto details on form
var url = "/GetShipTo/Customer"
$.ajax({
cache: false,
async: false,
type: "POST",
url: url,
data: { "id": ui.item.id },
success: function (data) {
$('.modal-body').show();
$("#Ship_To_Address_1").html(data.Ship_To_Address_1)
$("#Ship_To_Address_2").html(data.Ship_To_Address_2)
$("#Ship_To_City_Name").html(data.Ship_To_City_Name)
$("#Ship_To_State_Code").html(data.Ship_To_State_Code)
$("#Ship_To_Zip_Code").html(data.Ship_To_Zip_Code)
action = data.Action;
},
});
}
});
};
$('#myModalContent').find('.autocomplete_with_hidden').each(createAutoComplete);
});
Jquery Bind Form:
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajaxSetup({
cache: false
})
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#myModal').removeData("modal");
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
Related
I am trying to select the file name in my DropDownList to then call my GetFile function with the name file of the select box to then output it in a TextArea.
But i am unable to pass the data to GetFile( nameFile)
My DropDownList that contains my xml files name:
<div class="card" style="padding:20px">
<h4 class="mb-0">Sélection d'un fichier model XML </h4>
#Html.DropDownListFor(model => model.ListeFichiers, ((Dictionary<string, string>)Model.ListeFichiers).Select(e => new SelectListItem() { Text = e.Key, Value = e.Value }).ToList(),
new { #class = "form-control", #id = "listeFichierTransmettre" })
</div>
My GetFile function which takes as a parameter the filename retrieved from DropDownList
public string GetFile(string nomFichier)
{
string path = #"C:\xmlFiles\" + nomFichier;
string fileContent;
using (StreamReader streamReader = new StreamReader(#path, Encoding.UTF8))
{
fileContent = streamReader.ReadToEnd();
}
return fileContent;
}
After that i want to output the GetFile string returned in a TextArea :
<div class="card-body" id="XMLResult">
#Html.TextArea("Info", new { cols = "75", rows = "15", #readonly = "readonly", #disabled = "disabled", style = "min-width:100% !important;" })
</div>
What i tried but my file name is always null so clearly i am doing something wrong:
$(document).ready(function () {
$("#listeFichierTransmettre").change(function () {
$.ajax({
type: "POST",
url: '/Information/GetFile',
data: $('#listeFichierTransmettre').serialize(),
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
change script to :
$(document).ready(function() {
$("#listeFichierTransmettre").change(function() {
$.ajax({
type: "POST",
url: '/Information/GetFile',
data: {
nomFichier: $("#listeFichierTransmettre").find(":selected").val()
},
dataType: 'json',
success: function(result) {
console.log(result);
$("#Info").val(result);
}
})
return false;
});
});
I need to populate Cascading Country, State and City DropDownLists using jQuery AJAX in ASP.Net MVC.
This is the tutorial
https://www.aspsnippets.com/Articles/Cascading-Dependent-Country-State-City-DropDownLists-using-jQuery-AJAX-in-ASPNet-MVC.aspx
And working correctly.
My problem is validate these DropDownList when send the form
#Html.DropDownListFor(m => m.CountryId, Model.Countries, "[ === Select CountryId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.CountryId, "", new { #class = "text-danger" })
#Html.DropDownListFor(m => m.StateId, Model.States, "[ === Select StateId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.StateId, "", new { #class = "text-danger" })
In this moment if on the DropDownList no value is selected the form is validate.
How to do resolve this?
My View javascript part follow
#section Scripts {
<script src="https://code.jquery.com/jquery-1.10.2.js"
integrity="sha256-it5nQKHTz+34HijZJQkpNBIHsjpV8b6QzMJs9tmOBSo="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#StateId");
DisableDropDown("#CityId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option>[ === Select CountryId === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
}
</script>
}
Why not implement something like this:
if ($(this).val() == "") {
// return validation message
return;
}
else
{
value = $(this).val();
}
I have this code in cshtml file
#using (Html.BeginForm("UserPermission", "UserPermision", new { area = "Admin", id = "cbbDpm", name = "cbbDpm" }, FormMethod.Post))
{
#Html.DropDownListFor(m => m.Dept, new SelectList(Model.Dept, "DepartmentName", "DepartmentName"), "-- Select Department --", new { #class = "form-control w-100", #id = "cbbDpmt", #name = "cbbDpmt" })
}
...
<div id="partialDiv">
#Html.Partial("_Table")
</div>
...
<script>
$(document).ready(function () {
$("#cbbDpmt").on("change", function () {
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname' + $(this).val(),
type: 'GET',
data: "",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
});
});
</script>
And in controller, I have:
[HttpGet]
public PartialViewResult CBBSelectedChange(string dpmname)
{
List<AdminUserPermission> userModels = DatabaseServer.ConvertDataTable<AdminUserPermission>(DatabaseServer.Read_Table(#"SELECT *
FROM dbo.tblWFX_UserGroup AS gr
JOIN dbo.tblWFX_Department AS dpm ON gr.DepartmentName = dpm.DepartmentID
WHERE dpm.DepartmentName = " + dpmname, false));
Session["selectedDept"] = dpmname;
AdminUserPermissionParty adminUserPermissionParties = new AdminUserPermissionParty();
adminUserPermissionParties.UserPermisionModel = userModels;
return PartialView("_Table", adminUserPermissionParties);
}
I want put selected item from combobox in cshtml into function in controller. I try to research many time but I can't put selected value from cbb into string dpmname.
Please help me.
You need to use [FromUri]
[HttpGet]
public PartialViewResult CBBSelectedChange([FromUri] string dpmname)
And also change Ajax call as follows:
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname=' + $(this).val(),
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
See: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Hi i have one field in my view. That field is Customer it is a dropdown field. In that i have keep dropdown as select option to select the value. But i like to change that field as Autocomplete dropdown.
In the above image I have customerName field as dropdown field but i keep it by search and select option. But now i like to change this to autocomplete dropdown like which is mention the in the below image.
My view Code
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
My jquery Code
$(function () {
debugger;
$.ajax(
'#Url.Action("GetVisitCustomer", "VisitorsForm", new { Area = "Sales" })',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
});
My Controller Code to get Customers and load in the field
public JsonResult GetVisitCustomer()
{
var objCustomerlist = (from c in db.Customers where c.IsDeleted== false select c).ToList();
return Json( objCustomerlist,JsonRequestBehavior.AllowGet);
}
I tried to explain my issue. Any one help to resolve this issue. I tried many ways but its not working. So any one understand my issue and give some solution or suggesstions.
The Code which i have tried
My View Code
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.TextBoxFor(Model=>Model.CustomerID)
My Jquery Code
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").autocomplete({
source: function (request, response) {
$.ajax(
'#Url.Action("GetVisitCustomer", "VisitorsForm", new { Area = "Sales" })', {
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return
{ label=item.CustomerID, value= item.DisplayName
};
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
But this code is not working
Advance Thanks..
Kindly see code below:
HTML
#Html.LabelFor(model => Model.CustomerName, new { #class = "control-label" })
#Html.TextBoxFor(model => Model.CustomerName, new { #class = "form-control"})
#Html.HiddenFor(model => Model.CustomerID)
JS
$(document).ready(function () {
$("#CustomerName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetVisitCustomer", "Home")',
datatype: "json",
data: {
Areas: 'Sales',
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
customerId: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#CustomerID").val(ui.item.customerId);
}
});
});
CODE
public JsonResult GetVisitCustomer(string Areas, string term = "")
{
var objCustomerlist = db.Customers.Where(c => c.IsDeleted == false)
.Where(c => c.CustomerName.ToUpper()
.Contains(term.ToUpper()))
.Select(c => new { Name = c.CustomerName, ID = c.CustomerID })
.Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
Sample screenshot
I am trying to implement auto-populate on a particular textbox but it is not working so far. Here's my code. What am I missing?
VIEW:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Project/AutoCompleteOrganisation",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Organisation, value: item.Organisation };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="form-group">
<label for="#Html.IdFor(x => x.Organisation)">
#Html.DisplayNameFor(x => x.Organisation)
</label>
#Html.TextBoxFor(x => x.Organisation, new { #class = "form-control", data_project = "organisation", editorId="lead-organisation" })
#Html.ValidationMessageFor(x => x.Organisation)
</div>
My CONTROLLER:
[AjaxOnly]
public ActionResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var result = from org in organisationList.Organisation
where org.Name.ToLower().Contains(term.ToLower())
select org.Name;
return Json(result, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
I have also downloaded this:jquery.autocomplete.js and added it on my BundleConfig.cs
.Include("~/Scripts/jquery.autocomplete.js")
I was able to finally make it work.
Used this instead:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: '#Url.Action("AutoCompleteOrganisation", "Project")'
});
})
</script>
For controller:
public JsonResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var match = organisationList.Organisation.Where(x => x.Name.ToLower().Contains(term.ToLower())).
Select(e => e.Name).Distinct().ToList();
return Json(match, JsonRequestBehavior.AllowGet);
}
Then I did not download any autocomplete plugin, instead just use:
jquery-ui-1.10.4.custom.css
jquery-ui-1.10.4.custom.js
jquery-2.1.1.js
Thank you for answering my queries.