ASP.NET MVC jquery checkboxlist post? - asp.net-mvc

post methot:
function PostChartValues(meter_id, range_type_id, start_date, end_date) {
var values = $("#type_selection").val();
//values = expected values as string array
$.ajax({
url: '/Widget/GetMeterReadingsTimeSeries',
type: 'POST',
data: { MeterType: meter_id, DateRangeType: range_type_id, StartDate: start_date, EndDate: end_date, Parameters: values },
beforeSend: function () {
$("#chart_loading_div").show();
},
complete: function () {
$("#chart_loading_div").fadeOut();
$(".grids").jqGrid('GridUnload');
grid(meter_id, range_type_id, $("#start_date").val(), $("#end_date").val());
},
success: function (result) {
$("#chart").html(result);
},
error: function (result) {
alert("Seçilen kritere uygun veri bulunamadı!");
}
}); //end ajax
} //end PostChartValues
action method:
public ActionResult GetMeterReadingsTimeSeries(int MeterType, int DateRangeType, DateTime? StartDate, DateTime? EndDate,string[] Parameters)
{
// ...
return PartialView("_TimeSeries", chart);
}
I debugged it. only Parameters array is null. Is there an other way to post array with jquery post?
Thanks.

You can post selected values as string then you parse it back to array. I have created basic sample below,
Markup
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#someButton').click(function () {
var selectedValues = [];
$('#MyDiv input:checked').each(function () {
selectedValues.push($(this).val());
});
console.log(selectedValues);
$.ajax({
url: 'someurl',
type: 'POST',
data: { values: selectedValues.join(",") }
});
});
});
</script>
<button id="someButton">Do Ajax</button>
<div id="MyDiv">
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
</div>
Controller
public class HomeController : Controller
{
public void Test(string values)
{
string[] selectedValues = values.Split(',');
}
}

An alternate way to get the selected values if you're using Underscore:
var selectedValues = _.map($("#myDiv:checked"), function (item) { return $(item).val(); });

Related

method is called twice

What was I doing wrong?
My method is called twice.
First time I get Id and it's correct behavior
Second time I get Null
I can't get it what is correct way to solve it?
My View
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
<a class="btn btn-primary" data-index="#item.Id" name="link">Go to anywhere</a>
</div>
</div>
</div>
</div>
}
</div>
</div>
My Controller
[HttpGet]
public ActionResult ListCoach(int id)
{
if (id != null)
{
var ChoachList = _TraningService.Coach(id);
return View(ChoachList);
}
return HttpNotFound();
}
Script
I use script on My View use helper #Section {}
#section scripts {
#*<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>*#
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn)
});
});
</script>
}
if I use the method:
I can't get into View ListCoach
Can I return Json on My View?
[HttpGet]
public JsonResult ListCoach(int id)
{
var ChoachList = _TraningService.Coach(id);
return Json(ChoachList,JsonRequestBehavior.AllowGet);
}
Your code seems to be OK and in theory, your action should not call twice but I want to show you some ways in order to catch the problem:
when a call is made to the server in chrome developer tools in the tab network you will see a record in which there is a column named Initiator that shows you the call is created by who and where.
you can use keyword DEBUG in the first of function PassToContoller and look at the stack to know who one call your function
and about your final question, my answer is negative and you can not use this way to pass JSON object to your view but you can pass JSON object beside model by ViewBag or ViewData
In your function PassToContoller,in ajax success,you use window.location.href = '/TrainingType/ListCoach';,so after you call the function,it will have two requests,one with ajax,one with window.location.href.
If you want to get jsondata in ajax,you need to use dataType: "json", in ajax.
Here is a demo to pass json data:
Action:
[HttpGet]
public JsonResult GetJson(int id)
{
return new JsonResult(new TestModel { Id=id,Name="Test"});
}
View:
<button onclick="test()">
test
</button>
#section scripts
{
<script>
function test() {
$.ajax({
type: "GET",
url: 'GetJson',
data: { id: 1 },
dataType: "json",
success: function (data) {
console.log(data);
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
</script>
}
result:
Update:
You can try to use a form to pass Id to action(without using <a></a>):
<form asp-action="GetJson" asp-route-id="#item.Id">
<input type="submit" value="Go to anywhere" />
</form>
Action:
[HttpGet]
public IActionResult GetJson(int id)
{
return View("Index",new List<TestModel> { new TestModel { Id = id, Name = "Test" } });
}

Unable to pass Id from listbox items in mvc 5

I've coded for multiple values that resides inside listbox on button click. I have used autocomplete textbox to get the required value along with its id. Then i managed to add those values inside the listbox. Now what i want is to pass id's against those values in listbox instead of names. Below is my code that I'm running.
StudentBatch.cs
public string studentId { get; set; }
public string StudentName { get; set; }
public List<string> selectedids { get; set; }
public List<string> names { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div id="hiddensq">
</div>
for (int i = 0; i < Model.names.Count; i++)
{
#Html.Hidden("UserValues", Model.names[i]);
}
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.names))
<div id="partialDiv">
#{
Html.RenderPartial("GetListBox", Model);
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, id: item.Id };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$(function () {
$('#addtypevalue').click(function (e) {
var name = $("#StudentName").val();
alert(name);
$('#SelectedNames').
append($("<option></option>").
attr("value", name).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='"+ name +"'/>");
});
});
</script>
StudentController.cs
public ActionResult Create()
{
Context.Student student = new Context.Student();
Models.StudentBatch studBatch = new Models.StudentBatch();
studBatch.names = new List<string>();
studBatch.names.Add("Add Student Names");
studBatch.BatchNumberList = student.getBatchList();
return View(studBatch);
}
[HttpPost]
public JsonResult CreateStudent(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "f14570f0-e7a1-4c22-bf69-60ffbeb7e432";
var StudentList1 = user.GetAllUsers().ToList().Where(u => u.FirstName.Contains(Prefix) && u.usertypeid == stdid);
var StudentList = user.GetAllUsers().ToList();
var searchlist = (from student in StudentList1
where student.FirstName.Contains(Prefix)
select student).ToList();
return Json(StudentList1, JsonRequestBehavior.AllowGet);
}
// POST: Student/Create
[HttpPost]
public ActionResult Create(Models.StudentBatch student, IEnumerable<string> UserValues)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
If I understood correctly the problem here is passing multiple IDs from a listbox to a POST? One possible way is to assign viewbag like thus in your controller:
ViewBag.StudentList = new SelectList(db.StudentBatch, "studentId", "StudentName");
I use entities to access my models, I think you have a little bit different approach but the point is to give a collection to the Selectlist. Then you specify the data value field and the data text field.
Then in your view, note that it's not ListBoxFor, as it's dynamic:
#Html.ListBox("StudentList", null)
Then finally to be able to receive the values in the POST add the following parameter to your action and you should be able to iterate through it:
string[] StudentList
Finally managed to get the related from the listbox. I followed the instruction mentioned in a particular question. That's how i did.
$("#StudentName").autocomplete({
source: function (request, response) {
$.ajax({
cache: false,
// async: false, NEVER do this
url: '#Url.Action("CreateStudent", "Student")', // don't hard code your url's
data: { Prefix: request.term }, // change
dataType: "json",
type: "POST",
// contentType: "application/json; charset=utf-8", delete
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
id: item.id
}
}));
}
})
},select: function(event, ui) {
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("GetDetails", "Student")',
data: { id: ui.item.id },
success: function (data) {
var name = $("#StudentName").val();
$('#SelectedNames').
append($("<option></option>").
attr("value", ui.item.id).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='" + ui.item.id + "'/>");
}
});
}
});
</script>
and in the controller class
[HttpPost]
public JsonResult GetDetails(string id)
{
ViewBag.Value = id;
return Json(ViewBag.Value, JsonRequestBehavior.AllowGet);
}

Get and Set Value in drop downdown in MVC4

I am a beginer ...I don't know how to use dropdown in MVC this....I have used it like this
In ItemMaster.cshtml
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
In Controller.cs
public ActionResult ItemMaster(Item model)
{
ObservableCollection<Item> ItemList = new ObservableCollection<Item>();
Item Item = new Models.Item();
ItemList = Item.GetItemList();
Item Product = new Item();
DataTable dtProduct = new DataTable();
dtProduct = Item.GetProductList();
IList<Item> MyList = new List<Item>();
foreach (DataRow mydataRow in dtProduct.Rows)
{
MyList.Add(new Item()
{
Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
Product_Name = mydataRow["Name"].ToString().Trim()
});
}
var ProductName = new SelectList(MyList, "Id", "Product_Name");
ViewData["ProductName"] = ProductName;
return View(ItemList);
}
I am using Item list to fill grid view.... And I am using view data to fill drop down list....It is working fine.... I don't know how to get selected value when Button is clicked.
Try this,
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
<input type="button" id="btnasd" value="Click"/>
Script
<script type="text/javascript">
$(document).ready(function () {
$("#btnasd").click(function () {
var Id = $("#ProductName").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: "Post",
data: { ProductNameId: Id },
success: function (result) {
$("#mygrid").html('');
$("#mygrid").append(result.Data);
}
});
});
});
</script>
Do following(for onchange event of DropDownList):
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-", new { onchange = "doFunction();" })
javascript:
<script type="text/javascript">
$(document).ready(function () {
doFunction();
});
function doFunction() {
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
}
</script>
Or On button click
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-")
<input type="button" id="btnSubmit" value="Submit"/>
script:
$('#btnSubmit').click(function(){
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
});
Ask me if you have any query.
Note: You can also use DropDownListFor for model binded dropdown.

How to perform the following ajax request on jQuery Accordion?

I've created a jQuery Accordion using Asp.Net MVC, and it's working fine. The accordion displays a list of employee names, and when I click on an item, it shows the details. I'd like to send an AJAX request to get the employee details when they click on an item, instead of loading all the employee details at once. Please look at my code below.
Also, please tell me how to keep the first item in the accordion collapsed instead of showing the details, and is there any way to move the heading a bit to the right without using &nbsp?
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
</div>
}
</div>
<script>
$(function () {
$("Accordion").click(function (evt) {
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data:
//need code to pass the employeeid that was clicked on the accordion,
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
}
});
</script>
Here's a sample to send an AJAX request to the controller:
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv" data-id="#item.EmployeeId">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
<p><input type="button" id="Accordion" class="btn" name="Accordion" /></p>
</div>
}
</div>
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data: { employeeId : employeeId},
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
});
});
</script>
And in your controller:
[HttpGet]
public ActionResult GetEmployeeDetails(int employeeId)
{
// code: get the details based on employeeId
var detail = new Model.EmployeeDetail();
return Json(detail, JsonRequestBehavior.AllowGet);
}
Thiago's implementation seems like it should work. However, I would create a partial view _EmployeeDetails with how you want the details to look, based on the Employee model,
#model Employee
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
In your controller you'll return it as such,
public ActionResult GetEmployeeDetails(int employeeId)
{
...
var employee = Repository.GetEmployee(employeeId);
return PartialView("_EmployeeDetails", employee);
}
Which result you can use to the set the content of each <div id="accordionDiv"> on the AJAX response,
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: #Url.Action("GetEmployeeDetails"),
type: 'POST',
data: { employeeId : employeeId },
success: function (data) { parentDiv.html(data); }
});
});
});
</script>

jquery ajax call from asp.net mvc app

I am trying to call an action from jQuery. The action should return true or false,
and based on the return value I will do something.
I have the following code.
$("#payment").click(function (e) {
if($("#deliverytime").attr("disabled")){
//something here...
}
else
{
var postcode=$('#Postcode').val();
var restId='<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid="+restId+"&&postcode="+postcode;
$.ajax({
type: "GET",
url: URL
}).done(function(msg) {
if(msg==true){
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
else{
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
});
}
});
The code is not working. It says 'msg' is not defined. Is this not the way I should do this using jQuery-ajax? What am I doing wrong?
EDIT:
Controller action
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(Boolean.FalseString, JsonRequestBehavior.AllowGet);
}
else
return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
}
Modified function
var postcode = $('#DeliveryInfo_Postcode').val();
var restId = '<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid=" + restId + "&&postcode=" + postcode;
$.ajax({
url: URL,
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
$('#commonMessage').html(data);
return false;
}
}
});
EDIT -2
<script>
$(document).ready(function () {
$("#checkout").click(function (e) {
getDeliveryInfo();
});
});
function getDeliveryInfo() {
var URL ="/Restaurant/DoesRestaurantDeliver/6/2259"
$.get(URL, function (data) {
alert(data.isValid);
});
}
</script>
<%using (Html.BeginForm())
{ %>
<input type="submit" name="submit" id="checkout"/>
<%} %>
The above code does not work. But If i put the 'checkout' button out side of the form like below, it works.
<%using (Html.BeginForm())
{ %>
<%} %>
<input type="submit" name="submit" id="checkout"/>
You can configure your ajax call like below.
I feel your ajax call having problems on .done(function(msg) {} area.
Try to set success: function (data) {} like below.
<script type="text/javascript">
$(function () {
var companyName = $("#companyname");
$.ajax({
url: "/Company/GetName",
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
companyName.html(data.companyName);
}
}
});
});
</script>
EDIT
Action method should looks like below (This is a sample.Adjust it according to your situation)
[HttpGet]
public JsonResult GetName(string term)
{
var result = Repository.GetName(term);
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT 2
I would use Anonymous object (isValid) (remember that JSON is a key/value pairs):
Action Method
[HttpGet]
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(new { isValid = false},JsonRequestBehavior.AllowGet);
}
else
return Json(new { isValid = true },JsonRequestBehavior.AllowGet);
}
And then inside the ajax method:
success: function(data) {
if (data.isValid) {
...
}
}
EDIT 3
Just change your button type as below.(since you're not sending any values from form)
<input type="button" name="submit" id="checkout"/>

Resources