I have two drop down lists setup in an MVC view as follows:
#Html.DropDownListFor(model => model.Market,
new SelectList(ListInfo.Markets(), "Name", "Name"), "Markets..."
, new { #class = "form-control", #id = "MarketSelect" })
<select id="StationSelect" name="SelectedStations" class="chosen-select form-control" multiple></select>
The form beings with:
#using (Html.BeginForm("CreateEvent", "Event", FormMethod.Post, new { role = "form", id = "EventForm", data_stationListAction = #Url.Action("StationList") }))
The following script is called at the bottom of the view with:
<script src="#Url.Content("~/Scripts/marketStation.js")"></script>
$(function () {
$('#MarketSelect').change(function () {
var URL = $('#EventForm').data('stationListAction');
$.getJSON(URL + '/' + $('#MarketSelect').val(), function (data) {
var items = '<option>Stations</option>';
$.each(data, function (i, station) {
items += "<option value='" + station.Value + "'>" + station.Text + "</option>";
});
$('#StationSelect').html(items);
$("#StationSelect").trigger("liszt:updated");
$("#StationSelect").change();
});
});
});
Finally, I have a Controller Action as follows:
public ActionResult StationList(string market) {
string Market = market;
var stations = from s in ListInfo.Stations()
where s.MarketName == Market
select s;
if(HttpContext.Request.IsAjaxRequest())
{
return Json(new MultiSelectList(
stations.ToArray(),
"SalemOrgObjID",
"Name"),
JsonRequestBehavior.AllowGet);
}
return RedirectToAction("CreateEvent");
}
ListInfo.Stations looks like this:
public static IQueryable<StationData> Stations(){
return db.Stations.ToList().AsQueryable();
}
The first Drop Down List is Populating Fine (MarketSelect), but once a Market is selected, the Station List is not populated.
Any help is greatly appreciated.
.trigger() needed to be changed to .trigger("chosen:updated");
Related
Goal: I'm setting up the checkout page for my website and would like to have the user select from a list of their addresses. When they select it, it will add it to the cache and save it for when they have everything set up and are ready to complete their order.
Issue: When selecting the address, and pressing save changes, it returns 0 instead of the actual value of the item and I don't know why.
Here's the form:
Here's the view:
#model AirmotionEcommerceWebsite.Models.Home.CheckoutModel
#{
ViewBag.Title = "Checkout";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
<h1>Checkout</h1>
<form>
<div class="jumbotron row product-container">
<div class="col-md-4">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.UserAddresses;
}
<div class="form-group">
<h4>To Address:</h4>
#Html.DropDownListFor(model => model.selectedShippingAddress.IntShippingAddressId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedShippingAddress.IntShippingAddressId, "", new { #class = "text-danger" })
<a asp-controller="Home" asp-action="AddShippingAddress">Add New Address</a>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal" data-target="#ValidateAddress"
data-url="#Url.Action("CheckoutChanges", new { intShippingAddressID = Model.selectedShippingAddress.IntShippingAddressId })">Verify Address</button>
</div>
</div>
</div>
</form>
</div>
<script>
$(function () {
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
})
})
})
</script>
Here's the controllers:
[Authorize]
public ActionResult Checkout()
{
// get userid
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
// get addresses for this user
ViewBag.UserAddresses = GetShippingAddresses(userId);
CheckoutModel model = new CheckoutModel();
model.selectedShippingAddress = new TwebShippingAddress();
bool AlreadyExists = memoryCache.TryGetValue<CheckoutModel>("CachedModel", out model);
if (!AlreadyExists)
{
model = new CheckoutModel();
model.selectedShippingAddress = new TwebShippingAddress();
var cachEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
memoryCache.Set("CachedModel", model, cachEntryOptions);
}
return View(model);
}
[HttpGet]
public ActionResult CheckoutChanges(int intShippingAddressID)
{
if (intShippingAddressID == 0)
return View();
CheckoutModel model = new CheckoutModel();
bool AlreadyExists = memoryCache.TryGetValue<CheckoutModel>("CachedModel", out model);
if (AlreadyExists)
{
model.selectedShippingAddress = context.TwebShippingAddresses.Where(x => x.IntShippingAddressId == model.selectedShippingAddress.IntShippingAddressId).FirstOrDefault();
var cachEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
memoryCache.Set("CachedModel", model, cachEntryOptions);
}
return View();
}
Lastly, this is the GetShippingAddresses() method:
public IEnumerable<SelectListItem> GetShippingAddresses(string strUserID)
{
List<SelectListItem> list = new List<SelectListItem>();
var cat = context.TwebShippingAddresses.Include(x => x.IntState).Where(x => x.IntWebUserId == strUserID).OrderByDescending(x=>x.BlnIsDefault);
foreach (var item in cat)
{
list.Add(new SelectListItem { Value = item.IntShippingAddressId.ToString(), Text = item.StrName + " " + item.StrAttnTo + " " + item.StrStreet1 + " " + item.StrStreet2 + ", " + item.StrCity + " " + item.IntState.StrStateCode + " " + item.StrZip });
}
return list;
}
Replace the $.get like this to pass a Json object that will be auto binded to the action's parameter:
<script>
$(function () {
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
int selectedIndex = //Write jquery code to get the selected index here
$.ajax({
type: 'GET',
url: url,
data: { intShippingAddressID: selectedIndex },
dataType: 'json',
})
.success(function( data ) {
PlaceHolderElement.html(data);
});
})
})
</script>
Note the Json data type and the property that match the parameter of the Action.
I know this question is on a lot of others here. But here is my issue regarding the matter.
My Json Call in homecontroller:
public JsonResult GetBrand(int id)
{
List<String> resultdata = new List<String>();
//get some data via sql query
using (SqlCommand command = new SqlCommand(query, sqlconn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
resultdata.Add(reader.GetString(0));
}
}
}
return Json(resultdata, JsonRequestBehavior.AllowGet);
}
My 2nd Dropdown's code:
#Html.DropDownList("Brand", new SelectList(string.Empty, "", ""), "Please select", new { #class = "form-control" })
I also tried:
#Html.DropDownList("Brand", new SelectList(string.Empty, "div_id ", "material_name "), "Please select", new { #class = "form-control" })
And my script:
$(document).ready(function () {
$("#category").change(function () {
$.get("GetBrand", { id: $("#category").val() }, function (data) {
console.log(data);
$("#Brand").empty();
$.each(data, function (index, row) {
console.log(row);
$("#Brand").append("<option value='" + row.div_id + "'>" + row.material_name + "</option>")
});
});
})
});
On Chrome's F12 console, I can see this actual list of data I want returned in the dropdown and it is correct (via console.log(row);).
However, in the dropdown itself, it shows undefined.
Does anyone have any suggestions to what I am missing?
This was my fix for anyone also missing something so simple:
while (reader.Read())
{
items.Add(new SelectListItem
{
Value = Convert.ToString(Convert.ToInt32(reader["div_id"])),
Text = reader["material_name"].ToString()
});
}
Now it returns values.
I have two tables one is country table another one is doctor table both contains country fields.if i select any country name from country based on the country name i want to display doctors name from the doctor table.
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInputEmail1">Country</label>
#Html.DropDownList("CountryID", null, "--- Select Country ---", new { #class = "select2-arrow" })
#Html.ValidationMessageFor(model => Model.CountryID, null, new { #style = "color: red" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInput">Doctor Name</label>
<select id="UserRefID" class="select2-arrow"></select>
#Html.ValidationMessageFor(model => Model.UserRefID, null, new { #style = "color: red" })
</fieldset>
</div>
Country bind Code:
#region Country
public void Country_Bind()
{
userType type = new userType();
DataSet ds = type.Get_Country();
List<SelectListItem> coutrylist = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
coutrylist.Add(new SelectListItem { Text = dr["CountryName"].ToString(), Value = dr["CountryID"].ToString() });
}
ViewBag.CountryID = coutrylist;
}
#endregion
DAL :
public DataSet Get_Country()
{
SqlCommand cmd = new SqlCommand("Select * From Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
Doctor Bind based one country ID
#region Doctor Bind
public JsonResult Company_Bind(string CountryID)
{
userType type = new userType();
DataSet ds = type.Get_Doctor(CountryID);
List<SelectListItem> Doctorlist = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
Doctorlist.Add(new SelectListItem { Text = dr["Tittle"].ToString() + " " + dr["DoctorName"].ToString(), Value = dr["DoctorID"].ToString() });
}
return Json(Doctorlist, JsonRequestBehavior.AllowGet);
}
#endregion
public DataSet Get_Doctor(string CountryID)
{
SqlCommand com = new SqlCommand("Select * from DoctorRegistration where Country=#Country", con);
com.Parameters.AddWithValue("#Country", CountryID);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
<script>
$(document).ready(function () {
$("#CountryID").change(function () {
var id = $(this).val();
$("#UserRefID").empty();
$.get("Company_Bind", { CountryID: id }, function (data) {
var v = "<option>--- Select State ---</option>";
$.each(data, function (i, v1) {
v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
});
$("#UserRefID").html(v);
});
});
});
</script>
If i use [Authorize] i cann't use ajax function
//[Authorize]
//[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
public ActionResult Register()
{
UserType_Bind();
Country_Bind();
//Doctor_Bind();
return View();
}
if i don't use [Authorize] working fine
You are passing the string Company_Bind as the url for the ajax call. So it will be appended to the current pages url and a call will be made to that.
For example, if your currrent page is yourBaseUrl/Home/Index, the call will be made to yourBaseUrl/Home/index/Company_Bind?CountryID=4
If your current page is yourBaseUrl/Doctors/List, the call will be made to yourBaseUrl/Doctors/List/Company_Bind?CountryID=4
This will give you 404 response as that is invalid url to your action method.
You should consider using the Url.Action helper method to generate the correct relative path to the action method, irrespective of your current page.
So if your javascript code was inside a razor view,you can directly use it like
$.get("#Url.Action("Company_Bind")", { CountryID: id }, function (data) {
});
Or use the Url.Action overload which accepts the action method name and controller name.
$.get("#Url.Action("Company_Bind","Doctors")", { CountryID: id }, function (data) {
});
If it is in an external js file, you can still use the Url.Action helper in the razor view to generate the url and pass it to the external js file as explained in this post.
I have WebGrid on MVC project with two WebGrid column. The first column collapses the sub-data and the other column is for checkbox.
This checkbox will check all checkbox on its subdata. The problem is I cannot select all the data on its sub-checkbox. This is my sample code:
//This colum will generate checkbox for the main data
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parmain' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
//This column will generate another column for the sub-data:
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parsub' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
This is my javascript to select all checkbox on class: obj-parsub when my checkbox with class: obj-parmain is check
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function (e) {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//var objNext = $('.obj-parsub').nextAll();
//var objNextMain = $(this).siblings().nextAll().find('.obj-parsub');
//var objNextMain = $(this).closest('.obj-parmain').find('.obj-parsub').prop('checked', this.checked);
$(this).closest('.obj-parmain').find('.obj-parsub').parent().parent().nextAll().prop('checked', this.checked);
//$(objNextMain).prop('checked', blIsCheck);
}
});
}
try with this code. first you check your checkbox is checked or not.
$(document).on('change', '.obj-parmain', function (e) {
if ($(this).is(':checked')){
$('input:checkbox.obj-parsub').prop('checked', $(this).prop('checked'));
}
else{
// uncheck logic
}
});
Try like this
$(document).on('change', '.obj-parmain', function (e) {
$('.obj-parsub input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
If you encounter the same problem, this works pretty well:
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function () {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//This will look for the sublist of checkbox that is under class name obj-parsub and checks everything
var objNext = $(this).parent().parent().find('.obj-parsub');
$(objNext).prop('checked', blIsCheck);
}
});
}
This is my Get action method to get posts with their image:
public JsonResult GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
PostedByName = post.ApplicationUser.UserName,
PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
and this is my GetFileData action method to retrieve the images from the database:
public FileResult GetFileData(int fileId)
{
var file = db.Files.Single(x => x.FileId == fileId);
return File(file.Content, file.ContentType);
}
and this is the method which will generate url:
private string _GenerateAvatarUrlForUser(int? Id)
{
var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == Id);
if (avatarImage != null)
return Url.Action("GetFileData", new { fileId = avatarImage.FileId });
return String.Empty;
}
and this is the view page to show the user name with their pic but i am not able to show pic:
<div>
<div id="ajaxDiv">
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
var div = $('#ajaxDiv');
div.html("<br /> " + "Users received from server: " + "<br />");
$.each(data, function (i, item)
{
printUser(div, item);
});
});
});
function printUser(div, item)
{
div.append("<br/>" + "UserName: " + item.PostedByName + "<br/>" + "Pic: " + item.PostedByAvatar);
// I am stuck here on how to append image to this div or how to pass item.PostedByAvatar to this img src tag
div.append("<img src= + item. />");
<img src="#Url.Action("GetFileData", "Home", new { id = item.Id })" style="width:100px;height:100px;"/>
}
</script>
the url which i am successfullly getting back is like this:
/Post/GetFileData?fileId=2
how to resolve this ???
In your GetFileData action the parameter name in fileId. But when you are setting the source of image you are using the parameter name id which should be fileId like below.
#Url.Action("GetFileData", "Home", new { fileId = item.Id })
Update: As you said this should work.
div.append('<img class=cssClassName src="' + item.PostedByAvatar +'"/>');