I have 2 select field in ascx file:
<%=Html.DropDownList("CityID", new SelectList(Model.Cities, "Code", "Name"), new Dictionary<string, object>
{
{"class", "styled"}
})
%>
<%=Html.DropDownList("EstablishmentID", new SelectList(Model.Establishments, "OID", "Name"),
"All Establishment", new Dictionary<string, object>
{
{"class", "styled"}
})
%>
I want that a values of EstablishmentId change when user select new value in CityID.
How can I do this?
Thanks.
PS. ViewEngine is WepPages.
cascading Country and state DDL
#Html.DropDownListFor(model => model.CountryId, Model.CountryList, "--Select Country--", new { #class = "CountryList", style = "width:150px" })
#Html.DropDownListFor(model => model.StateId, Model.StateList, "--Select State--", new { #class = "StateList", style = "width:150px" })
<script type="text/javascript">
$(document).ready(function () {
$.post("/Client/GetModels", { id: $(".CountryList").val() }, function (data) {
populateDropdown($(".StateList"), data);
});
$(".CountryList").change(function () {
$.post("/Client/GetModels", { id: $(this).val() }, function (data) {
populateDropdown($(".StateList"), data);
});
});
});
function populateDropdown(select, data) {
$(".StateList").empty();
$.each(data, function (id, option) {
$(".StateList").append("<option value='" + option.StateId + "'>" + option.State + "</option>");
});
}
</script>
Try this
In view
<div class="popup_textbox_div" style="padding: 0pt;">
<%=Html.DropDownList("CityId", new SelectList(Model.Cities, "Code", "Name", 0), "---Select City---", new { #class = "popup_textbox popup_dropdown valid" })%>
</div>
<div class="popup_textbox_div" style="padding: 0pt;">
<select class="popup_textbox popup_dropdown valid" id="OID" name="Name">
<option>---All Establishment---</option>
</select>
</div>
Add the script
<script type="text/javascript">
$(function () {
$("#CityId").change(function () {
var cityId = $("#CityId").val();
if (!isNaN(cityId) && ( cityId > 0) && ( cityId != null)) {
GetEstablishmentsByAjax(cityId);
}
else {
$("#OID").html("<option value=''>---All Establishment---</option>");
}
});
});
GetEstablishmentsByAjax(cid) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/trail/selectestablishment/" + cid.toString(),
data: "",
dataType: "json",
success: function (data) {
if (data.length > 0) {
var options = "<option value=''> --All Establishment---</option>";
for (s in data) {
var type = data[s];
options += "<option value='" + type.Value + "'>" + type.Text + "</option>";
}
$("#OID").html(options);
}
}
});
}
</script>
In TrailController
public ActionResult selectestablishment(int? id)
{
SelectList establishments = null;
var estb = //put ur code and get list of establishments under selected city
establishments = new SelectList(estb, "OID", "Name");
return Json(establishments, JsonRequestBehavior.AllowGet);
}
Related
I have problem with my dropdownlist design when i select the first dropdownlist the second dropdownlist will refresh but the design has been change
After I select a value from the country dropdownlist, a province dropdown design may suddenly change:
Here is my view
<div class="form-group">
<label class="control-label col-md-2">Country</label>
#Html.DropDownListFor(x => x.CountryNames, Model.CountryNames, "--Select--", new { #id = "ddlState", #class = "form-control" })
</div>
<div class="form-group">
<label class="control-label col-md-2">Province</label>
<div id="Province">
#Html.DropDownListFor(x => x.ProvinceNames, new List<SelectListItem>(), "--Select--", new { #id = "ddlProvince", #class = "form-control" })
</div>
</div>
And this is my script function:
$(document).ready(function () {
$('#ddlState').change(function () {
$.ajax({
type: "post",
url: "/ContactAddress/GetProvince",
data: { stateId: $('#ddlState').val() },
datatype: "json",
traditional: true,
success: function (data) {
var district = "<select id='ddlProvince'>";
district = district + '<option value="">--Select--</option>';
for (var i = 0; i < data.length; i++) {
district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
district = district + '</select>';
$('#Province').html(district);
}
});
});
});
I change my code instead of .html i used append but my Province dll no data shows
$('#ddlState').change(function () {
$.ajax({
type: "post",
url: "/ContactAddress/GetProvince",
data: { stateId: $('#ddlState').val() },
datatype: "json",
traditional: true,
success: function (data) {
var district = "<select id='ddlProvince'>";
district = district + '<option value="">--Select--</option>';
for (var i = 0; i < data.length; i++) {
district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
district = district + '</select>';
$('#dllProvince').append(district);
}
});
});
});
You are completely removing the dropdown from the html tree and rebuilding it by adding html to your div. Better way would be to remove the current options like
$('#ddlProvince')
.empty();
and then append the options. Your function should look like this.
success: function (data) {
var district = "";
$('#ddlProvince').append('<option value="">--Select--</option>');
for (var i = 0; i < data.length; i++) {
$('#ddlProvince').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option>');
}
}
this one working for me thank you for giving solution
$(document).ready(function () {
$('#ddlState').change(function () {
$('#ddlProvince').empty();
$.ajax({
type: "post",
url: "/ContactAddress/GetProvince",
data: { stateId: $('#ddlState').val() },
datatype: "json",
traditional: true,
success: function (data) {
var district = "<select id='ddlProvince'>";
district = district + '<option value="">--Select--</option>';
for (var i = 0; i < data.length; i++) {
$('#ddlProvince').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option>');
}
}
});
});
});
I am trying to make the helper #Html.EnumDropDownListFor searchable with an input tag on it. That way I can type to search for an item in the huge list. I preferably want to make this hard coded without other plugins. Can someone help me?
Here is the code:
<div>Escolha aqui o banco de sua preferĂȘncia:</div>
#Html.EnumDropDownListFor(model => model.BankPaymentMethods, " ", htmlAttributes: new {#class = "form-control"})
The EnumDropDownListFor helper only generates <select> elements. The closest you can get without a plugin would be an input with a datalist and the list attribute.
Assuming your enum is called BankPaymentMethod and BankPaymentMethods is an IEnumerable of some sort, and your model has a PaymentMethod property:
#Html.TextBoxFor(m => m.PaymentMethod, new { #class = "form-control", list = "payment-methods" })
<datalist id="payment-methods">
#foreach(var method in Model.BankPaymentMethods)
{
<option value="#method">#method</option>
}
</datalist>
For reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist.
Typically its done inside a text box, I guess you can do it inside a Select by appending the value and name also you need to paste your VM or selectList VMModel. I have made some assumptions, code is not tested, but with a couple change and hopefully it will help you.
#Html.TextBoxFor(model => model.BankPaymentID)
#section scripts{
// you can update to the latest version of Jquery-ui, I put in the most compatible version for you
<script src="~/Scripts/jquery-ui-1.15.1.js">script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.15.1/themes/base/jquery-ui.css">
<script>
$(function () {
$("#BankPaymentID").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Searchable")', // server action
datatype: "json",
data: {
term: request.term // this what you are searching
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
BankPaymentID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$.get("/Home/GetBankPaymentMethods", { BankPaymentID: ui.item.BankPaymentID }, function (data) {
$("#PaymentID").empty();
$.each(data, function (index, row) {
$("#PaymentID").append("<option value='" + row.PaymentID + "'>" + row.PaymentName + "option>")
});
});
}
})
})
script>
}
Controller Searchable Action
public ActionResult Searchable(string term)
{
if (!String.IsNullOrEmpty(term))
{
var list = db.banks.Where(c=>c.PaymentName.ToUpper().Contains(term.ToUpper())).Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
else
{
var list = db.banks.Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
}
I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}
I have declared the webgrid inside a div in a partial view and my delete button is in Main View.Now I want a functionality in which when i click the delete button my webgrid should get refreshed only not whole page(Main View).
**I want to refresh only partial View which Contains webgrid using jquery in mvc
My partial View Code is as follows:
WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station");
//WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "grid1");
string Message = "";
if (#ViewBag.NoData != null)
{
Message = ViewBag.NoData.ToString();
}
<div id="UserMainDiv">
#if (Model.Count() > 0)
{
<div id="grid1" class="row container" style="width:84%;margin-left:8%;">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;padding-left:0px;padding-right:0px;">
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
//mode: WebGridPagerModes.All,
//firstText: "",
//lastText: ">>",
//previousText: "<",
//nextText: ">",
columns: grid.Columns
(
//Here I am going to add checkbox column
//Here I am going to add checkbox column
grid.Column(format: #<text> <input type="checkbox" value="#item.ID" name="ids" /> </text>, header: "{checkall}"),
//grid.Column("ID"),
#*grid.Column("Name",format: #<text>#Html.ActionLink((string)item.Name, "AddEdit", "gridchk", new { id = item.id })</text>),*#
grid.Column("Station", format: #<text>#Html.ActionLink((string)item.Station, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightNo", "Flight No", format: #<text>#Html.ActionLink((string)item.FlightNo, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightDate", "Flight Date", format: #<text>#Html.ActionLink((string)item.FlightDate.ToString("MM/dd/yy"), "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("FlightDate", "Flight Date", format: (item) => item.FlightDate != null ? item.FlightDate.ToString("MM/dd/yy") : "NULL"),
grid.Column("PaxNo", "Pax No", format: #<text>#Html.ActionLink((string)item.PaxNo != null ? (string)item.PaxNo : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNo", "Pax No", format: (item) => item.PaxNo != null ? item.PaxNo : "NULL"),
grid.Column("PaxNoOwnward", "PaxNo Onward", format: #<text>#Html.ActionLink((string)item.PaxNoOwnward != null ? (string)item.PaxNoOwnward : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNoOwnward", "PaxNo Onward", format: (item) => item.PaxNoOwnward != null ? item.PaxNoOwnward : "NULL"),
grid.Column("TextMsg", format: #<text>#Html.ActionLink((string)item.TextMsg, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>)
)
)
</div>
</div>
}
#*</div>*#
else
{
<div style="width:80%;margin-left:10%;">
<div class="row container">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;text-align:center;">
#Html.Label("", Message, new { id = "lblMessage" })
</div>
</div>
</div>
}
</div>
And My Main page view where i have delete button button code declared.
With that I am using Jquery
$('#btnDelete').click(function (e) {
var command = $('#btnDelete').val();
var myArray = [];
$("#gridtable tbody tr td:nth-child(1)").find('input[type="checkbox"]:checked').each(function () {
myArray.push(($(this).val()));
});
e.preventDefault();
var url = '#Url.Action("DeleteUser", "CreateUser")';
$.ajax({
url: url,
type: 'GET',
data: { ids: myArray },
dataType: 'html',
success: function (data) {
// $("#demoaArea").html(data);
location.reload();
// window.location.href = url;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error; ' + eval(error));
alert("Status: " + textStatus); alert("Error: " + errorThrown);
//alert('Error!');
}
});
});
My Delete controller code:
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
}
In your ajax call success, instead of reload , use the below one.
$('#UserMainDiv').html(data)
and in your controller return partialview instead of whole view.
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
return PartialView("PartialViewName",model);
}
I am new to MVC and would like to know, how to submit whole grid data on submit button click to controller at once using viewmodel.
In View
#model prjMVC4Training.Models.BookViewModel
#{
ViewBag.Title = "Index";
var categories = ViewBag.BookCategories;
var authors = ViewBag.BookAuthors;
var grid = new WebGrid(source: Model.BookData, canSort: true, canPage:true);
}
#using (Html.BeginForm("BookPost", "Book", FormMethod.Post, new { #id = "grid" }))
{
<h2>Book Index Page</h2>
#Html.HiddenFor(m => m.PrimaryKeyID)
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns(
grid.Column("Actions",
style: "col1",
canSort: false,
format: #<text>
<button type="button" class="edit-book display-mode" id="#item.BookID">Edit</button>
<button type="button" class="save-book edit-mode" id="#item.BookID">Save</button>
<button type="button" class="cancel-book edit-mode" id="#item.BookID">Cancel</button>
</text>),
grid.Column("BookTitle",
style: "col2",
canSort: true,
format: #<text>
<span id="dBookTitle" class="display-mode">#item.BookTitle</span>
#Html.TextBox("BookData_" + (int)item.BookID + "__BookID", (string)item.BookTitle, new { #class = "edit-mode", size = 45 })
</text>),
grid.Column("AuthorName",
header: "Author",
style: "col3",
canSort: true,
format: #<text>
<span id="dAuthorName" class="display-mode">#item.AuthorName</span>
#Html.DropDownList("AuthorID_" + (int)item.BookID, (ViewBag.BookAuthors as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.AuthorID
}), new { #class = "edit-mode" })
</text>),
grid.Column("CategoryName",
style: "col4",
canSort: true,
format: #<text>
<span id="dCategoryName" class="display-mode">#item.CategoryName</span>
#Html.DropDownList("CategoryID_" + (int)item.BookID, (ViewBag.BookCategories as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.CategoryID
}), new { #class = "edit-mode" })
</text>),
grid.Column("BookISBN",
style: "col5",
format: #<text>
<span id="dBookISBN" class="display-mode">#item.BookISBN</span>
#Html.TextBox("BookISBN_" + (int)item.BookID, (string)item.BookISBN, new { #class = "edit-mode", size = 20 })
</text>),
grid.Column("IsMember",
style: "",
format: #<text>
<span id="dMember" class="display-mode">#item.IsMember</span>
<input type="checkbox" id="MemberID_" + (int)item.BookID name="MemberID" #(item.IsMember == true ? "Checked" : null) class="edit-mode"/>
</text>)))
<button type="submit" value="Save Book Data">Save Book Data</button>
}
On submit button, I want to pass the value to controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BookPost(BookViewModel obj)
{
ViewBag.BookCategories = new SelectList(BookHelperData.GetBookCategories(), "CategoryID", "CategoryName", "20");
ViewBag.BookAuthors = new SelectList(BookHelperData.GetAuthors(), "AuthorID", "AuthorName");
//ViewBag.BookAuthors = BookHelperData.GetAuthorsList();
var Book = BookHelperData.GetBooks();
return View(Book);
}
My ViewModel Class is like this-
public class BookViewModel
{
public int PrimaryKeyID { get; set; }
public List<Book> BookData { get; set; }
}
You can write a generic method which loops all the data in grid and transform it to json structure.
function gridTojson() {
var json = '{';
var otArr = [];
var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
if ($(this)[0].rowIndex != 0) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"' + i + '": [' + itArr.join(',') + ']');
}
})
json += otArr.join(",") + '}'
return json;
}
Now on submit button click you need to pass the data to controller.
$('#btnsave').click(function (e) {
//debugger;
var _griddata = gridTojson();
var url = '#Url.Action("UpdateGridData")';
$.ajax({
url: url,
type: 'POST',
data: { gridData: _griddata }
}).done(function (data) {
if (data != "") {
$('#message').html(data);
}
});
});
Now on controller serialize the data back
public ActionResult UpdateGridData(string gridData)
{
var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
return Json("Update Successfully");
}
Here is the post regarding this.