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
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 have a dropdownlist contains a list of products which binds from database. I want to load selected product Data.
here is my code in view
#Html.DropDownListFor(model => model.ProductName, new SelectList(Model.ProductsList, "ProductID", "ProductName"), new
{
id = "Productslist",
#class = "GreenDropDownListStyle",
#datastyle = "dropdown",
#onchange = "FillProduct()"
})
I had use java Script code to send select Product Id then get it's data
<script type="text/javascript">
$(document).ready(function () {
$("#Productslist").change(function () {
debugger;
var selectedIndex = $(this).val();
var divH = document.getElementById(selectedIndex);
if (selectedIndex > 0) {
$.ajax(
{
url: '/Inventory/ViewProduct',
type: 'GET',
data: { ProductID: selectedIndex },
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
},
error: function () {
alert("error");
}
});
}
else {
divH.style.visibility = 'hidden'; // Hide
}
});
});
</script>
the issue that this code send the selected index not the is for the selected product also its send the id as a string so it never go to my condition
last thing in case of succeed what i should write
it solved by
var ProductID = this.value;
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 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;
});
}
I am trying to bind JSON Data to dropdown list
My Scenario is I want to get data and Bind to dynamic dropdown list,
In Seperate Class, I have used linq to get data like
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
In Controller:
ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
In View:
#for (int i = 0; i <2; i++)
{ {
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #class = "ddlProjectvalue" })
}
Now, I am trying for like if we have three dropdownlist, we select a list item in first dropdown list should not show in second dropdown list, and in third dropdown list should not show both previous selected list items for that i have writtern script like:
<script>
$(document).ready(function () {
$('.ddlProjectvalue').change(function () {
debugger;
var selectedValue = $(this).val();
if (selectedValue != null && selectedValue != '') {
debugger;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Employer/GetDDLData?selectedValue="+selectedValue,
data: "{}",
dataType: "Json",
success: function (data) {
// first remove the current options if any
$('.ddlProjectvalue').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(data).each(function (index, item) { // GETTING ERROR HERE
debugger;
$('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
});
});
</script>
and I am returning JSON Data from Controller:
public ActionResult GetDDLData(string selectedValue)
{
int projectid = Convert.ToInt32(selectedValue);
IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
return Json(result, JsonRequestBehavior.AllowGet);
}
I have tried, but getting Error like
"Syntax error, Unrecognized Expression"
where I am Doing Wrong , please help me anyone.
This will help you :
$.ajax({
url: "#Url.Action("GetDDLData","Employer")",
data: {selectedValue:selectedValue},
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".ddlProjectvalue").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".ddlProjectvalue").append(optionhtml);
});
}
});
//Controller Code
public ActionResult getAccount()
{
var result = new SelectList(db.Partymsts, "Account", "Account");
return Json(result, JsonRequestBehavior.AllowGet);
}
// js code
$.ajax({
type: "POST",
url: "/NewMaster/getAccount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".cs3").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".cs3").append(optionhtml);
});
}
});
// html code
<select id="cs3" name="cs3" class="cs3 form-control input-small"> </select>
its working !!
If your json is correct the below will work.Put the code in your ajax success
success:function(data){
$('.ddlProjectvalue').empty();
$.each(data,function (index, item) {
$('.ddlProjectvalue').append$('<option>', {
value: item.Value,
text: item.Text
}, '<option/>')
}
);
}
We have done in this way
Dropdown.append($('<option></option>').val(item.col1).text(item.col2));
function GetDropDownData(stateid) {
$.ajax({
type: 'GET',
url: '#Url.Action("getdist","Home")',
data: {stateid:stateid},
dataType: 'json',
success: function(data)
{
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
$.each(data, function (id, result) {
$("#districtId").append('<option value"'+result.Value+'">'+result.Text+'</option>');
});
},
failure: function () {
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
}
});
}