Saving changes to the DB MVC - javascript

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()).

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);
}

asp.net-mvc ajax json post to controller action method

I know that same questions have answers, but they don't work in my project.
I have controller were i send message to employee.
id i take with ajax.
email i take from db. but getEmployeeEmail() returns me my email( it's right)
Controller name: EmployersActivity
Code don't work when i send post.
My ajax post code:
$(document).ready(function () {
$(".buttonSendEmail").click(function () {
var orderText = $(".orderData").text();
alert(orderText);
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "#(Url.Action("Create", "EmployersActivity"))",
data: { id: 1 },
dataType: "json",
traditional: true,
error: function (message) {
alert("error on start")
$(".contentReqGood").show();
redirect();
},
success: function (result) {
if (result.status === 1) {
alert("error")
} else {
$(".contentReqGood").show();
redirect();}})})});
asp.net mvc code:
[HttpGet]
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Create(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var email = db.employees.Find(id);
if (email == null)
return HttpNotFound();
if (email != null)
{
if (db.SaveChanges() == 1)
{
string mailTemplate;
string title = "asdasd";
string preview = "asdasdasd";
var sr = new StreamReader(Server.MapPath("~/App_Data/Templates/" + "InfoEmail.txt"));
mailTemplate = sr.ReadToEnd();
string messageBody = string.Format(mailTemplate, title, preview);
new MailSender
{
Sender = "news#omegasoftware.eu",
Recipient = "news#omegasoftware.eu",
RecipientsBcc = getEmployeeEmail(),
Subject = title,
Body = messageBody
}.Send();}}
return View();}
You have several issues regarding current example:
1) [Authorize] attribute is unnecessary on POST method because using it in GET action method should be enough to prevent unauthorized users.
2) Since you're sending AJAX request to a POST method which includes [ValidateAntiForgeryToken] attribute, it is necessary to send the CSRF prevention token into AJAX request.
3) Remove dataType: "json", contentType: 'application/json; charset=utf-8' and traditional: true since you're sending single integer data and not using an array or JSON-formatted string.
4) AJAX callbacks are intended to stay in same page, hence return View() should be replaced with return PartialView().
Based from 4 issues above, if it's necessary to use AJAX, you should set the request and controller action like following example below:
AJAX Request
$(document).ready(function () {
$(".buttonSendEmail").click(function () {
var orderText = $(".orderData").text();
alert(orderText);
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "POST",
url: "#Url.Action("Create", "EmployersActivity")",
data: { id: 1, __RequestVerificationToken: token },
error: function (message) {
alert("error on start");
// other stuff
},
success: function (result) {
$(".contentReqGood").show();
// other stuff
}
});
});
});
Controller Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var email = db.employees.Find(id);
if (email == null)
return HttpNotFound();
if (email != null)
{
// do something
}
return PartialView("_PartialViewName");
}
Other than that, if you want to pass entire viewmodel content to POST action method or use redirection with RedirectToAction() after submit, then you should use normal form submit (with Html.BeginForm() helper) instead.

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()
},

Passing data from JavaScript to MVC Controller

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.

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

Categories