Passing data from JavaScript to MVC Controller - javascript

Wellcome!
I have a problem with passing data from JavaScript to MVC Controller. Im new to MVC so I probably miss something.
$("#example").keypress(function (event) {
var data = "example";
$.ajax({
url: "/example/example",
type: "POST",
dataType: "json",
data: { example: data },
success: function (example) {
var items = "";
$.each(data, function (i, example) {
items += "<option>" + example + "</option>";
});
$("#example").html(items);
}
});
});
public class PeoplePickerController : BaseController
{
// GET: PeoplePicker
public ActionResult PeoplePicker(object data)
{
if (HttpContext.Request.IsAjaxRequest())
{
IQueryable logins = (IQueryable)QueryDatabaseForUsersAndGroups((string)data, Context.Users);
return Json(new SelectList(example, "example"), JsonRequestBehavior.AllowGet);
}
return PartialView();
}
}
data parameter is always null.

Related

Dynamic Downloading Data and set to DevExtreme TextBox

Description of the situation:
I have selectbox, I choose a person there (there, I download the entire list of employees from the database). I have two more fields (I would like to enter values ​​from other columns (same row) (data of this employee))
Controller
using AppEcp.Models;
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace AppEcp.Controllers
{
public class UzytkownicyController : Controller
{
private readonly UzytkownicyDbContext _uzytkownicyContext;
public UzytkownicyController(UzytkownicyDbContext uzytkownicyContext)
{
_uzytkownicyContext = uzytkownicyContext;
}
public IActionResult GetItems(DataSourceLoadOptions loadOptions)
{
var GetMethod = _uzytkownicyContext.Uzytkownicy.Where(i => i.Firma == "Pekao Leasing").Select(i => new
{
i.Id,
i.Nazwa,
i.Departament,
i.Login
});
return Json(DataSourceLoader.Load(GetMethod, loadOptions));
}
[HttpGet]
public ActionResult GetDepartmentAndManager(string nazwaValue)
{
var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Nazwa == nazwaValue).Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.Manager
});
return Json(danePracownika);
}
}
}
I tried:
cshtml page
#(Html
.DevExtreme()
.SelectBox()
.ID("Id_name")
.DataSource(d => d
.Mvc()
.Controller("Uzytkownicy")
.Key("Id")
.LoadAction("GetItems")
)
.DisplayExpr("Nazwa")
.ValueExpr("Id")
.SearchEnabled(true)
.OnValueChanged("getDepAndMan")
)
#(Html.DevExtreme().TextBox()
.ID("Id_department"))
#(Html.DevExtreme().TextBox()
.ID("Id_manager"))
<script type="text/javascript">
function getDepAndMan() {
var nazwaValue = document.getElementById("Id_name").value;
$.ajax({
type: "GET",
url: '#Url.Action("GetDepartmentAndManager", "Uzytkownicy")',
contentType: 'application/json; charset=utf-8',
data: { nazwaValue : nazwaValue},
dataType: "json",
success: function (data) {
document.getElementById("Id_department").value = (data.UserDepartament);
document.getElementById("Id_manager").value = (data.UserManager);
},
error: function () {
alert("bad code noob");
}
});
}
</script>```
Do not work:
The code does not throw an error, but does not enter the downloaded data into text boxes
Access the required widget using its "options" api (refer to this demo), for example:
success: function (data) {
alert(data.UserDepartament + " " + data.UserManager);
//document.getElementById("Id_department").value = (data.UserDepartament);
//document.getElementById("Id_manager").value = (data.UserManager);
$("#Id_department").dxTextBox("instance").option("value", data.UserDepartament);
$("#Id_manager").dxTextBox("instance").option("value", data.UserManager);
}

Saving changes to the DB MVC

I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).

Pass list javascript in parameter ASP.NET

i have a modal with input, i digit some emails and add to a list, later i want to pass this list of emails to my function that send emails.
var listEmails = [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
listEmails.push(text);
}
document.getElementById("sendEmail").onclick = function () {
#*location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails='+listEmails;
}
that is my function in Controller that receive a list of email to send
public void TestSendReport(List<string> ListMails)
Please try below code and try to call controller method using jQuery Ajax
var list= [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
list.push(text);
}
document.getElementById("sendEmail").onclick = function () {
var jsonText = JSON.stringify({ list: list});
$.ajax({
type: "POST",
url: "ProductMarketplace/TestSendReport",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("success"); },
failure: function() { alert("failed"); }
});
}
And use controller method like this,
[WebMethod]
public void TestSendReport(List<string> list)
{
}
document.getElementById("sendEmail").onclick = function () {
location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails=' +
encodeURI(JSON.stringify(listEmails));
}
public void TestSendReport(List<string> emails)
{
}

Pass table input to controller

I'm new to programming and I want to pass a table input value to the controller. I tried this:
$("#btnsend").click(function () {
$.ajax({
type: "POST",
contentType: "application/json ; charset=utf-8",
data: {
buyerID: $('.BuyerID').val(),
},
url: "/SaveReservation",
success: function (data) {
alert('buyerID : ' + data);
},
error: function (result) {
alert('something went wrong');
}
})
});
The controller is like this :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SaveReservation(BuyerModel buyer)
{
return Json(buyer.DistibutorID);
}
When I click the button I get a success state but in the alert I get all the source code of the project after the word buyerID.
You may want to try this:
return Json(new { success = true, message = buyer.DistibutorID },
JsonRequestBehavior.AllowGet);
And:
alert('buyerID : ' + data.message );
Notice that this here in your script
data: {
buyerID: $('.BuyerID').val(),
},
Either must have the same structure as your BuyerModel Here
public JsonResult SaveReservation(BuyerModel buyer) <- BuyerModel that you are using
{
return Json(buyer.DistibutorID);
}
Or you can Just Change your Controller to accept only one argument Like this
public JsonResult SaveReservation(string buyerID) <- Follow the same Object structure you are passing in Ajax
{
return Json(buyer.DistibutorID);
}

pass jquery array of objects to mvc action which accepts a list object

I have a form in my view which has only one textarea input initially and user can add more textarea inputs if he wants with jquery. My problem is related to second case. After submitting the form i am getting an array of objects in console but when i am passing this array to mvc action in my controller it is coming to be null.
I have tried these solution but did not succeed:
Send array of Objects to MVC Controller
POST a list of objects to MVC 5 Controller
here is my code:-
jquery code:
$('body').on('submit', '#addTextForm', function () {
console.log($(this));
var frmData = $(this).serializeArray();
console.log(frmData);
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify({ obj: frmData }),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
MVC action:
[HttpPost]
public string UploadText(SliderTextList obj)
{
return "success";
}
my object class:
public class SliderText
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("SlideName")]
public string SlideName { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
public class SliderTextList
{
public List<SliderText> AllTexts { get; set; }
}
I have to store the Content in json file with Id and SlideName, so i think i have to pass a list object in mvc action Uploadtext which is coming out to be null always. Please help.
$(document).ready(function(){
$('body').on('submit', '#addTextForm', function () {
var listData=[];
var oInputs = new Array();
oInputs = document.getElementsByTag('input' );
var k=1;
for ( i = 0; i < oInputs.length; i++ )
{
if ( oInputs[i].type == 'textarea' )
{
var obj=new Object();
obj.Id=k;
obj.SlideName=oInputs[i].Name;
obj.Content=oInputs[i].Value;
K=parseInt(k)+1;
listData.push(obj);
}
}
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify(listData),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
});
Since the sever side expects a string as argument obj as a query string I think this is what you need.
data: {
obj: JSON.stringify(frmData)
},
as an alternative using as Stephen suggested on the comments
data: {
obj: $('#addTextForm').serialize()
},

Categories