I'm trying to populate one select when the onchange of another select is called. Below is what I have built. My GetLine ActionResult breakpoint is being hit, but the parameter breweryCode is null. The method errors at that point. What am I missing?
Controller:
public ActionResult Index()
{
List<Brewery> breweries = BuildMockBrewery();
ViewBag.Breweries = new SelectList(breweries.AsEnumerable(), "BreweryCode", "BreweryDescription");
return View();
}
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
function GetLine(_breweryCode) {
var url = '/Report/GetLine/';
$.ajax({
url: url,
data: { breweryCode: _breweryCode },
cache: false,
type: "POST",
success: function (data) {
alert('called');
var markup = '<option value="0">Select Line</options>';
for (var i = 0; i < data.length; i++) {
markup += '<option value="' + data[i].Value + '">' + data[i].Text + '</options';
}
$('#LineSelect').html(markup).show();
},
error: function (response) {
alert('fail' + ' ' + _breweryCode);
}
});
}
</script>
<div id="report-description">
#using (Html.BeginForm("Index", "Report", FormMethod.Post))
{
#Html.DropDownList("BreweryCode", (SelectList)ViewBag.Breweries, "Select Brewery", new { #class = "ui-select", #ID = "BrewerySelect", #onchange = "javascript:GetLine(this.Value);" })
<select class="ui-select" id="LineSelect" name="ReportSelect">
</select>
}
In your #onchange attribute, change this.Value to this.value
Try add
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
so GetLine can be able to process POST request
Please add datatype as well:
dataType: 'html', or dataType: 'json'
and add http method in a controller
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
}
Also, make sure whether value _breweryCode is coming in below function
function GetLine(_breweryCode)
{
}
Take below code as sample
$.ajax({
type: "POST",
url: your url,
dataType: 'json',
data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('hello');
}
});
Related
I'm trying to bind jsonresult data to label text which are from database but it won't work..
I have posted script code herewith it will get dropdownlist selected value and pass to actionresult and then result data pass as jsonresult
<script>
function getOutletDetails() {
debugger;
var centreName = $("#ddl_Outlet").find("option:selected").text();
$.ajax
({
url: "#Url.Action("OutletDetails", "AddTickets", new {area="Common"})",
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ centreName: +centreName }),
success: function (result) {
$("#lblTelephone1").text(result.Telephone_01);
},
error: function () {
alert("Whooaaa! Something went wrong..")
},
});
}
</script>
Controller Code
[HttpPost]
public ActionResult OutletDetails(string centreName)
{
List<tbl_Centre> lstcity = new List<tbl_Centre>();
// int id1 = Convert.ToInt32(id);
//ViewBag.Id = id;
lstcity = (objbs.CentreBs.GetAll().Where(x => x.CentreName == centreName)).ToList<tbl_Centre>();
var result = JsonConvert.SerializeObject(lstcity, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return Json(result, JsonRequestBehavior.AllowGet);
}
Usually .text() will work like this
$('#sampleButton').click(function(){
$('#SampleId').text($('.userInput').val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="SampleId">Sample text</label><br><br>
<input class="userInput" style="width: 300px" type="text" value="new value that will be replace at label"><br><br>
<button id="sampleButton">change label text</button>
I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.
In controller class my action code is
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and my JavaScript code is
<button id='deleteRecord'>delete</button>
$("#deleteRecord").click(function () {
var StudentId = $(this).val();
var stdId = parseInt(StudentId);
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I shall be very thankful if anybody help me.
You need to add your model id in jquery data tag:
<button id='deleteRecord' data-model-id="#model.Id">delete</button>
Then in javascript code:
$("#deleteRecord").click(function () {
var StudentId = $(this).data("model-id");
var url = "/AjaxStudent/Delete/" + StudentId;
$.ajax({
url: url,
type: 'Delete',
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":
$.ajax({
url: "#Url.Action("Delete","AjaxStudent")",
type: "POST", // here is your problem,
data: { StudentId: stdId },
dataType: 'json',
success: function() {
alert("Deleted");
},
error: function(dat) {
alert(data.x);
}
});
And the action method in your controller must be decorated with [httppost] :
[HttpPost]
public JsonResult Delete(int StudentId)
{
using (StudentContext db = new StudentContext())
{
Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
you should try by changing :
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
to:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}
After lots of time I am able to resolve my problem.
Now my javaScript code
<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button>
$(".deleteRecord").click(function () {
var StudentId1 = $(this).data("stid");
debugger;
$.ajax({
url: "/AjaxStudent/Delete/" + StudentId1,
type: "Post"
}).done(function () {
getAllStudents();
});
});
});
Controller.cs
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
I went through a lot of guides and stacloverflow posts, but i still don't manage to make it work. I'm still new in javascript, and it's hard for me to figure if it's the script or not.
The main issue i got is the fact I'm not able to debbug it properly, i mean, i can't find where and why it's not working, i just know it doesn't.
Here is my Controller :
Entities db = new Entities();
// GET: DynamicListe
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string Prefix)
{
//Searching records from list using LINQ query
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select new { c.Nom });
return Json(client, JsonRequestBehavior.AllowGet);
}
Here is my View :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
I got the right amount of answers (when i press "w" i got 13 results which is correct according to my db), but it's all empty. I've tried severals ways to display the json datas, but i don't know how to make it work..
Edit : correct controller and view :
view :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Value};
}))
}
});
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
controller :
[HttpPost]
public JsonResult Index(string Prefix)
{
List<SelectListItem> list = new List<SelectListItem>();
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select c).ToArray();
for (int i = 0; i < client.Length; i++)
{
list.Add(new SelectListItem
{
Text = client[i].Nom,
Value = client[i].ClientID.ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);
}
You're returning your response before it has been received.
In here
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
Move the line response(customer) inside the ajac success callback.
You textbox does not have an ID. you have to add for yout textbox : #Id="client"
I am facing the problem when I am populating the DropDownList by JavaScript via MVC. I am getting the Uncaught TypeError: Cannot read property 'length' of undefined while populating the DDL.
My Code as define below
View:-
<div class="form-group">
<label>SubRetailer</label>
#Html.DropDownListFor(m => m.SubRetailer, Model.SubRetailerList, "All Selected", new { #class = "form-control", id = "SubParentRetailerDDL" })
</div>
Controller : -
public ActionResult getSubRetailer(int ParentRetailerID)
{
List<DashboardGetSubRetailer_Result> lstDesig = db.DashboardGetSubRetailer(ParentRetailerID).ToList();
return Content(JsonConvert.SerializeObject(lstDesig), "application/json");
}
JavaScripts function:-
function GetNames(ParentRetailerID) {
if (ParentRetailerID > 0) {
$("#SubParentRetailerDDL").get(0).options.length = 0;
$("#SubParentRetailerDDL").get(0).options[0] = new Option("Loading SubRetailer", "-1");
alert("ParentRetailerID : "+ ParentRetailerID);
$.ajax({
type: "POST",
url: "Search/getSubRetailer",
data: "{ParentRetailerID:" + ParentRetailerID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success : " + ParentRetailerID);
$("#SubParentRetailerDDL").get(0).options.length = 0;
$("#SubParentRetailerDDL").get(0).options[0] = new Option("Select SubRetailerName", "-1");
**$.each(msg.d, function (index, item) {
$("#SubParentRetailerDDL").get(0).options[$("#SubParentRetailerDDL").get(0).options.length] = new Option(item.SubRetailerName, item.SubRetailerID);
});
},**
error: function () {
alert("error : " + ParentRetailerID);
$("#SubParentRetailerDDL").get(0).options.length = 0;
alert("Failed to load SubRetailer");
}
});
}
else {
$("#SubParentRetailerDDL").get(0).options.length = 0;
}
}
I am facing the error at below step in java script. I am getting the data from Controller but not populating in DDL.
$.each(msg.d, function (index, item) {
$("#SubParentRetailerDDL").get(0).options[$("#SubParentRetailerDDL").get(0).options.length] = new Option(item.SubRetailerName, item.SubRetailerID);
});
I do not know what you are trying to do with that line. But if you are trying to replace the options of your second dropdown with the data coming from the server, you can simply do this.
$("#SubParentRetailerDDL").html(""); //Clear existing items
//loop through the items came back and append to dropdown
$.each(msg, function (index, item) {
$("#SubParentRetailerDDL")
.append("<option value='"+item.SubRetailerID+"'>"+item.SubRetailerName+"</option>");
});
Also there is no reason for you to explicitly Serialize the data to json format because there is already a Json method which does that for you.
public ActionResult getSubRetailer(int ParentRetailerID)
{
var data = db.DashboardGetSubRetailer(ParentRetailerID).ToList();
return Json(data , JsonRequestBehavior.AllowGet);
}
This code will work assuming your DashboardGetSubRetailer method returns a collection of items each with a SubRetailerID and a SubRetailerName property. If you have a single property called d which the collection, just udpate the $.each(msg with $.each(msg.d
Its working now as below
Changes in View--
<div class="form-group">
<label>Retailer</label>
#Html.DropDownListFor(m => m.Retailer, new SelectList(Model.lstParentRetailsDetails, "ParentRetailerID", "ParentRetailerName"), "All Selected", new { id = "ParentRetailerDDL", #class = "form-control" })
</div>
<div class="form-group">
<label>SubRetailer</label>
#Html.DropDownListFor(m => m.SubRetailer, new SelectList(Enumerable.Empty<SelectListItem>(), "SubRetailerID", "SubRetailerName"), "All Selected", new { #class = "form-control", id = "SubParentRetailerDDL" })
</div>
-- Inside Java Scripts
$().ready(function (msg) {
$("#ParentRetailerDDL").bind("change", function () {
GetNames($(this).val());
});
});
function GetNames(ParentRetailerID) {
if (ParentRetailerID > 0) {
$("#SubParentRetailerDDL").empty();
$.ajax({
type: "POST",
url: "Search/getSubRetailer",
data: "{ParentRetailerID:" + ParentRetailerID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$.each(msg, function (index, item) {
$("#SubParentRetailerDDL").append("<option value='" + item.SubRetailerID + "'>" + item.SubRetailerName + "</option>");
});
},
error: function () {
$("#SubParentRetailerDDL").get(0).options.length = 0;
alert("Failed to load SubRetailer");
}
});
}
else {
$("#SubParentRetailerDDL").get(0).options.length = 0;
}
}
I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...
For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});