How to pass Array to MVC Controller with Jquery? - javascript

I am beginner to develope .Net MVC 5 application. But I have some problem with passing array or object to controller with Jquery.
I'm adding dynamically input fields with button. I want to pass input's data to controller. But I couldn't succeed.
Html Section is like that;
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
Get Value button function is like that;
$("#getButtonValue").click(function () {
var list = new Array();
for (i = 1; i < counter; i++) {
list[i] = $('#textbox' + i).val();
alert(list[i]);
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Even I set "traditional" by true , the model is null.
[HttpPost]
public JsonResult PostQuestionAndOptions(string[] model)
{
return Json(true);
}
Could any one help me ? Thank you.

You need to have a strongly typed object.
JavaScript
$("#getButtonValue").click(function (e) {
e.preventDefault();
var list = [];
for (var i = 1; i < counter; i++) {
list.push($('#textbox' + i).val());
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Strongly typed object
public MyValues {
public list<string> values {get; set;}
}
Controller method
[HttpPost]
public JsonResult PostQuestionAndOptions(MyValues model) {
return Json(true, JsonRequestBehavior.AllowGet);
}

Related

Empty model when passing JSON data from View

I am currently trying to pass data from AJAX to Controller, however, the model always shows up empty/count = 0.
AJAX call:
$("#btnSubmit").click(function(e) {
e.preventDefault();
var _this = $(this);
var url = _this.closest("form").attr("action");
var rows = [];
var items = $(".itemRow");
$.each(items, function(i, item) {
var tbOne = $(item).find("input[name='tbOne']").val();
var tbTwo = $(item).find("input[name='tbTwo']").val();
var row = {
Test1: tbOne,
Test2: tbTwo
};
rows.push(row);
});
//Let's post to server
$.ajax({
type: "POST",
url: url,
data: rows,
contentType: "application/json"
})
.done(function(result) {
//do something with the result
})
});
});
Model:
public class Test
{
public string Test1 {get; set;}
public string Test2 {get; set;}
}
Controller:
[HttpPost]
public ActionResult Insert(<SomeOtherModel> otherModel, IEnumerable<Test> model)
{
foreach (var item in model)
{
// to do here
}
}
I am not sure what I am missing... I tried to search on other posts and they did relatively the same thing as I did. But I just can't get the data to my controller..
Firstly,you passed one model to controller,so the Action should have only one parameter.Furthermore,your contentType is"application/json",and you data is not json data.Besides,if you want to pass json data to controller,you need to use [FromBody].
Here is a demo worked:
Controller:
[HttpGet]
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert([FromBody]IEnumerable<Test> model)
{
return View();
}
View:
#{
ViewData["Title"] = "Insert";
}
<h1>Insert</h1>
<button id="btnSubmit">submit</button>
#section scripts{
<script type="text/javascript">
$("#btnSubmit").click(function () {
var rows = new Array();
var row = {};
row.Test1 = "test1";
row.Test2 = "test2";
rows.push(row);
var row1 = {};
row1.Test1 = "test11";
row1.Test2 = "test21";
rows.push(row1);
var model = JSON.stringify(rows);
//Let's post to server
$.ajax({
type: "POST",
url: "Insert",
data: model,
contentType: "application/json; charset=utf-8"
});
});
</script>
}
Result:

Unable to retrieve data from html

As for my below code i am not able to get sectionID from tr, i need to get dynamic id of sectionID on each delete button click but it is always giving me null
Here is the Jquery Script :
<script>
$(function () {
$('.btnDelete').click(function () {
var sectionID = $(this).closest('tr').find('.sectionID');
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'CheckSectionIDagainststudentID',
data: JSON.stringify({ sectionID: sectionID.html() }),
success: function (data) {
if (data == true) {
$.alert("Cannot delete | Students exsisting in this
Section!");
}
else if (data == false) {
var secCode = JSON.parse(this.data);
var code = sectionid['sectionid'];
window.location.href = "SectionDelete?Page=data&sectionid="
+ code;
}
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
and here is Razor Page
#foreach (var item in Model)
{
<tr class="sectionID">
<td >
#Html.DisplayFor(modelItem => item.sectionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td class="secCode">
<button style="width:49.5%" ID="Button2" type="button" onclick="location.href='#Url.Action("SectionEdit", "Section",new { id = item.sectionID, name = item.name })'">Edit</button>
<button style="width:49.5%" ID="deletebtn" runat="server" type="button" onclick="location.href='#Url.Action("SectionDelete", "Section",new { id = item.sectionID, name = item.name })'">Delete</button>
<button class="btnDelete">Delete</button>
</td>
</tr>
}
This is Controller Which i need to pass data to
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
return Json(sectionID);
}
As per your question you are not able to get value from var sectionID = $(this).closest('tr').find('.sectionID');
therefore here is a way you can achieve your result
//Your Dynamic Button should look like this
//in value Bind your sectionID # MVC
<button class="btnDelete" value="5" onclick="AjaxDelete(this)">Delete</button>
//For Function
function AjaxDelete(values) {
//Write this in Ajax
//Fetch Value from attribute value
var sectionID = $(values).attr("value"); // you will get 5 as value
//Your Ajax Call with SectionId as Parameter
}
Edit :
as you have got value
U can split the value by below code
where string is your var of sectionID
if ((~string.indexOf('\n '))) {
string= string.split('\n ')[1].split('\n')[0];
}
Use string array :
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string[] sectionID)
{
return Json(sectionID);
}

Populate dropdown based on another dropdown selection Spring MVC AJAX

I have 2 dropdowns: one for categories and one for subcategories. Based on what category I select on the first dropdown I want that the second dropdown to be dynamically populated with the subcategories of the selected category. This is what I have so far:
Controller to populate the first dropdown:
#RequestMapping(value = "/post_project", method = RequestMethod.GET)
public String postProjectPage(Model model) {
Project project = new Project();
List<Category> categoriesList = categoryService.getAllCategories();
model.addAttribute("projectForm", project);
model.addAttribute("categoriesList", categoriesList);
return "post_project";
}
JSP:
<form:form id="post_project" action="/post_project" method="post" modelAttribute="projectForm">
<form:select class="form-control" id="selectCategory" path="category">
<option value="">-Select-</option>
<form:options items="${categoriesList}" itemValue="id" itemLabel="category_name"/>
</form:select>
For the subcategories I have the following controller:
#RequestMapping(value = "/post_project", method = RequestMethod.POST)
public #ResponseBody List<Subcategory> getAllSubcategories(#RequestParam(value="categoryId") int categoryId) {
return categoryService.getAllSubcategories(categoryId);
}
JSP:
<form:select class="form-control" id="selectSubcat" path="subcategory">
<option value="-1" label="-Select-"/>
</form:select>
For populating the second dropdown I used AJAX, but I am very new with this and I don't know if it is right.
("#selectCategory").change(function(){
var categoryId = $(this).val();
$.ajax({
type: 'POST',
url: "/post_project",
data: {"categoryId" : categoryId},
success: function(data){
var slctSubcat=$('#selectSubcat'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error:function(){
alert("error");
}
});
});
Of course it does not work. When I select a cateogry nothing shows up in the second dropdown. I don't know what to do anymore and I've tried everything. Can someone please tell me what I am doing wrong?
Make you request as a GET:
("#selectCategory").change(function(){
var categoryId = $(this).val();
$.ajax({
type: 'GET',
url: "/categories/" + categoryId,
success: function(data){
var slctSubcat=$('#selectSubcat'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error:function(){
alert("error");
}
});
});
Server Side controller method:
#RequestParam is used to get the query parameters. So, it would be like ..../post_project?categoryId=1
Instead of #RequestParam use #PathVariable as below:
So to get the subcategories, you have #RequestMapping like .../categories/1
#RequestMapping(value = "/categories/{categoryId}", method = RequestMethod.GET)
public #ResponseBody List<Subcategory> getAllSubcategories(#PathVariable("categoryId") int categoryId) {
return categoryService.getAllSubcategories(categoryId);
}
Try to add the contentType & dataType to your Ajax Call :
` ....
$.ajax({
type: 'POST',
url: "/post_project",
data: {"categoryId" : categoryId},
contentType:"application/json; charset=utf-8"
dataType:"json",
........`
and change your controller to Post a Json Request :
#RequestMapping(value = "/post_project", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)

Pass button ID to the controller in AJAX calls

In my webpage I have different cities to select using buttons and i want to retrieve my data from my model based on the button ID. Since i have 400+ records for each city.
If I click on my button looks like it is not activating my controller method because my ajax call is not happening
my HTML code looks like this:
<table>
<tr>
<td id="A"><input value="A"type="button" id="btn_a" onclick="getValues(this)"/>
</td>
</tr>
<tr>
<td id="B"><input value="B"id="btn_b" type="button" onclick="getValues(this)"/>
</td>
</tr>
</table>
myController method
public JsonResult updateValues(string site)
{
list<string> dataList = new list<string>;
Model m = new Model();
dataList = m.myData(site);
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(dataList );
return Json(dataList , JsonRequestBehavior.AllowGet);
}
my Ajax call.
<script type="text/javascript">
function getValues(siteID) {
var id = siteID.id,
var data = id.value,
$.ajax({
type: "GET",
url: '#Url.Action("updateValues")',// the method we are calling
cache: false,
contentType: "application/json; charset=utf-8",
data: {"data": data},
dataType: "json",
success: function (data) {
for (var k = 0; k < 630; k++) {
document.getElementById(k).innerHTML = data[k];
}
}
});
}
</script>

how send table content to controller

I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.
but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah
Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/

Categories

Resources