How to receive data from ajax send() method in a controller - ajax

I'm trying to serve the data in the ASP.NET MVC controller sent by ajax POST. On client side I use traditional XMLHttpRequest object and send() method instead of jQuery.ajax().
Do you know how to get variables from send() in controller? In documentation http://www.xul.fr/XMLHttpRequest-object.html I've read that it has to be string.
My client-side:
var data1 = "some string";
var data2 = "other string";
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://localhost:44301/Home/SaveDataInDB", true);
xhr.send(data1, data2);
xhr.onreadystatechange = saved;
My server-side:
[HttpPost]
public JsonResult SaveDataInDB(string data1, string data2)
{
var dbobj = new DbObj
{
field1 = data1,
field2 = data2
};
if (User.Identity.IsAuthenticated)
{
dbobj.user = User.Identity.Name;
}
else
{
dbobj.user = "anonymous";
}
db.DbObj.Add(dbobj);
db.SaveChanges();
return Json(true);
}

You can do like this, lets say this is your xmlHttpRequest -
<script type="text/javascript">
var request = new XMLHttpRequest();
var o = new Object();
o.data1 = "Rami";
o.data2 = "Ramilu";
request.open('POST', '/Home/xhr', true);
request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
request.setRequestHeader('Content-Length', JSON.stringify(o).length);
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.send(JSON.stringify(o));
</script>
On the server side, have a ViewModel defined this way -
public class XhrViewModel
{
public string data1 { get; set; }
public string data2 { get; set; }
}
Then your controller action which want to get this data -
public ActionResult xhr(XhrViewModel model)
{
return Content("success", "text/plain");
}
And the output would be -

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

How to pass dictionary item from client side (Ajax) to server side (MVC API)

I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});

HttpPost with AJAX call help needed

what else do i need in my code please, I have this so far:
<script type="text/javascript">
function PostNewsComment(newsId) {
$.ajax({
url: "<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").val(), success: function (data) {
$("#news-comment-content").html(data + $("#news-comment-content").html());
type: 'POST'
}
});
}
$("#textareaforreply").val("");
</script>
and
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(int newsId, string newsComment)
{
if (!String.IsNullOrWhiteSpace(newsComment))
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(newsId, newsComment, currentUser.UserId);
Zinc.DataModels.News.NewsCommentsDataModel model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return null;
}
<div class="actions-right">
<%: Html.Resource(Resources.Global.Button.Reply) %>
</div>
i have no idea how this works, because it is not working in FF???
and the other thing is i must not pass return null i must pass JSON false ???
any help please?
thanks
You should encode your request parameters. Right now you have concatenated them to the request with a strong concatenation which is a wrong approach. There's a property called data that allows you to pass parameters to an AJAX request and leave the proper url encoding to the framework:
function PostNewsComment(newsId) {
$.ajax({
url: '<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>',
type: 'POST',
data: {
newsId: newsId,
newsComment: $('#textareaforreply').val()
},
success: function (data) {
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
});
}
Also you haven't shown where and how you are calling this PostNewsComment function but if this happens on the click of a link or submit button make sure that you have canceled the default action by returning false, just like that:
$('#someLink').click(function() {
PostNewsComment('123');
return false;
});
and the other thing is i must not pass return null i must pass JSON false ???
You could have your controller action return a JsonResult in this case:
return Json(new { success = false });
and then inside your success callback you could test for this condition:
success: function (data) {
if (!data.success) {
// the server returned a Json result indicating a failure
alert('Oops something bad happened on the server');
} else {
// the server returned the view => we can go ahead and update our DOM
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
}
Another thing you should probably be aware of is the presence of dangerous characters such as < or > in the comment text. To allow those characters I would recommend you build a view model and decorate the corresponding property with the [AllowHtml] attribute:
public class NewsViewModel
{
public int NewsId { get; set; }
[AllowHtml]
[Required]
public string NewsComment { get; set; }
}
Now your controller action will obviously take the view model as argument:
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(NewsViewModel viewModel)
{
if (!ModelState.IsValid)
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(viewModel.NewsId, viewModel.NewsComment, currentUser.UserId);
var model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return Json(new { success = false });
}

Post list and variable to WebApi using jQuery Ajax

I am trying to post a list of data and a variable to WebApi using jQuery Ajax.
My clientside code is:
var datatopost = new Object();
for(var i=0;i<results.length;i++)
{
datatopost["[" + i + "].NodeID"] = results[i];
}
var result;
result = grandtotal;
$.ajax({
type: "POST",
url: createurl,
dataType: "json",
traditional: true,
data: "{ 'node': '" + datatopost + "',ttl: '" + result + "'}",
statusCode: {
200: function () {
alert("success");
}
},
error:
function (res) {
alert('Error');
$("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText);
}
});
My server-side code is
public HttpResponseMessage PostBuy([FromBody]List<Node> node, decimal ttl)
{
//Success code here
return new HttpResponseMessage(HttpStatusCode.OK);
}
I am receiving a bad request error in the network tab of the inspect element.
Is there any problem with my code?
I'm not completely sure, but it may be related to the "node" element in your JSON. It looks to be an object and not an array. Verify that the data is being sent properly in its JSON form.
here is my way to post a list with some other values, I post a JSON.stringify string,
var o = {};
o.UserCode = userCode;
o.Role = role;
o.UserId = r.d;
o.Hotels = [];
$('#hotel-list li :checkbox:checked').each(function () {
var ctrl = $(this);
var h = {};
h.ChainId = ctrl.val();
h.ProjectId = ctrl.next().val();
h.CityId = ctrl.next().next().val();
o.Hotels.push(h);
});
$.post("/home/UpdateDataToDb/", { d: JSON.stringify(o) }, function (r) {
alert(r.Msg);
});
and my server side code is this:
[System.Web.Mvc.HttpPost]
public JsonResult UpdateDataToDb(string d)
{
var jsonStr = d;
var json = JsonConvert.DeserializeObject<QueryPostData>(jsonStr);
//json.UserCode
//json.Role
//json.UserId
foreach (var chain in json.Hotels)
{
//My code to handle list `Hotels`
}
}
and the QueryPostData is this
public class QueryPostData
{
public string UserCode { get; set; }
public string Role { get; set; }
public string UserId { set; get; }
public List<BriefChain> Hotels { get; set; }
}
public class BriefChain
{
public string ChainId { get; set; }
public string ProjectId { get; set; }
public string CityId { get; set; }
}

JSON returned using Json() by jquery $.post()

I can't work out what I'm doing wrong - I'm sure this used to work...:
<script type="text/javascript">
$("##containerId form").submit(function (event) {
event.preventDefault();
var form = $(this);
if (form.valid()) {
$.post(form.attr('action'), form.serialize(), function(data) {
$("##containerId").replaceWith(data.result);
}, "json");
}
});
</script>
I have a function that returns a view result as a string so I can return it as an object within the JSON response:
protected string RenderViewResultToString(ViewResultBase viewResult) {
using (var sw = new StringWriter()) {
if (string.IsNullOrEmpty(viewResult.ViewName))
viewResult.ViewName = ControllerContext.RouteData.GetRequiredString("action");
ViewEngineResult result = null;
if (viewResult.View == null) {
result = viewResult.ViewEngineCollection.FindPartialView(ControllerContext, viewResult.ViewName);
if (result.View == null)
throw new InvalidOperationException("Unable to find view. Searched in: " + string.Join(",", result.SearchedLocations));
viewResult.View = result.View;
}
var view = viewResult.View;
var viewContext = new ViewContext(ControllerContext, view, viewResult.ViewData, viewResult.TempData, sw);
view.Render(viewContext, sw);
if (result != null)
result.ViewEngine.ReleaseView(ControllerContext, view);
return sw.ToString();
}
}
So, in my controller I have:
[HttpPost, ValidateInput(false)]
public JsonResult Edit(/* stuff */) {
bool success = true;
try {
/* stuff */
} catch {
/* stuff */
success = false;
}
return Json(new { success, result = RenderViewResultToString(/* stuff - call to something that gives a ViewResult */) });
}
In Chrome, I get: "Resource interpreted as Document but transferred with MIME type application/json." and it renders the JSON in the browser as text.
In Firefox/IE, it prompts me to download a file.
What gives?
The form submission isn't getting suppressed. The messages you are getting are from an actual form submission to a page that returns JSON. If you check the browser address bar, you should see the URL is different.
If you run $("##containerId form") in the console, you should see that you're getting no results. "#" is an invalid character in a selector and needs to be escaped. $("#\\#containerId form") should work.

Resources