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.
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 am sort of lost on the coding part of this problem. I have a MVC application, and I am trying to populate a queries Where clause as the selected value from my drop down list. Also, I am populating the drop down list from a query in the database. For example:
SELECT db.ID FROM Database db where ID = 1232
Instead of that, I want to do something like this...
SELECT db.ID FROM Database db where ID = "SelectedValue from Dropdownlist"
Model Class:
public string ID {get; set;}
public string Summary{get; set;}
public int Estimate {get; set;}
public List<Hello> getIDs()
{
var que = (from wre in db.Table
select new Hello{
ID = wre.ID
}).toList();
}
Controller class:
public ActionResult Index(string? IDParam)
{
var model = test.getStuff();
var que = (from wre in db.View
where wre.ID == IDParam //Operator '==' cannot be applied to operands of type 'string' and 'string?'
select new Hello
{
ID = wre.ID
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
if (IDParam!= null & IDParam.HasValue)
{
model = model.Where(x => x.ID == IDParam); //Operator '==' cannot be applied to operands of type 'string' and 'string?'
}
return View(model);
}
View Class:
#Html.DropDownList("ID", ViewBag.Releases as SelectList, "ID", new {#id="rel" })
<table>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Estimate)</th>
</table>
<script>
$("#rel").change(function () {
var selectedId = this.val();
location.href = '#Url.Action("Index", "SampleController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
</script>
This works perfectly fine, but now, I am lost on the coding aspect of it. I can see the alert every time I change the ID from the drop down list. However, there is no change in the data being displayed (I know I am missing a lot). If anyone can help me out here, that would be great, thank you!
1) Try adding where clause in Linq
where wre.ID == IDParam
2) Change que to instance of your class and get firstOrDefault instead of List
3) Try passing instance of your class as a model in view
return View(test);
1- You need to get changed Id as below :
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
});
2- If you want to reload your page then you need to set a parametre to your [HttpGet] Method :
public ActionResult Index(int? selectedId) // selectedId
{
var que = (from wre in db.View
select new Hello
{
ID = IDParam
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
ViewBag.Releases = new SelectList(test.getIDs(), "", "ID");
var model = test.getStuff();
if(selectedId!=null && selectedId.HasValue)
{
// do some stuff with your selectedId
// if working method is test.getStuff(), then maybe you can use like code below:
model = model.Where(x=> x.Id==selectedId);
}
return View(model);
}
and in your View:
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
location.href = '#Url.Action("Index", "YourController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
3- If you dont want to reload page then you need to use Ajaxrequest, You must create a new method for get data by selectedId,
// Your view.
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
$.ajax({
method: "POST",
url: "'#Url.Action("GetDataBySelectedId","YourController")'",
data: { selectedId: selectedId }
})
.done(function( data) {
// Delete your table, and fill table with your data with jquery.
});
});
// your Controller:
[HttpPost]
public JsonResult GetDataBySelectedId(int? selectedId)
{
// Do some stuff for get your data.
var data = yourData.Where(x=> x.Id = selectedId.Value);
return Json(data);
}
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'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions !
could anyone help me ? what's the problem ?
I'm not good in javascript and I think problem would be in javascript codes :/
Thanks in advance
Goods controller
[HttpPost]
public ActionResult AddToCart(int Id, int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
Html = ""
});
}
}
public ActionResult RemoveCart(int Id)
{
try
{
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
else
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
Html = ""
});
}
}
MyJsonData.cs
public class MyJsonData
{
public string Script { get; set; }
public string Html { get; set; }
public bool Success { get; set; }
}
_GoodDetailsAjax.cshtml
#foreach (var item in Model.GoodDetails)
{
<div>
<p class="nowprice">NowPrice : #item.DetailsNowPrice</p>
<p class="preprice">PrePrice : #item.DetailsPrePrice</p>
<a class="button icon-cart" href="#" GoodID="#item.DetailsGoodID">Add to cart</a><br>
<a class="link" >Shopping Cart (0)</a>
</div>
}
#section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$(function () {
$("a.button.icon-cart").click(function (e) {
e.preventDefault();
var goodId = $(this).attr("GoodID");
alert(goodId); //////// I just added this code
$.ajax({
url: "/Goods/AddToCart",
data: { Id: goodId, Count: 1 },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("Error!");
}
});
});
});
</script>
}
I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:
Script = "alert('product added to your basket');"
So you can add this tag for the result:
<div id="CartItems">
</div>
Now it works without any problem.
All of my codes was true , I just made some simple mistakes .
I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .
And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view (GoodDetails.cshtml) and it works fine now .
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");