HttpPost with AJAX call help needed - ajax

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

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'

call to function from the controller in index.html

In my mvc app I have combobox, I am trying to do the following: when the user choose some item that will call to some function from the controller.
Index.html:
#using (Ajax.BeginForm("dor", "Home", new AjaxOptions
{
HttpMethod = "Get",
//UpdateTargetId = "myPic",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace
}))
{
#Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", #class = "form-control", onchange = "CallChangefunc()" })
}
.
.
.
<script type="text/javascript">
function CallChangefunc() {
window.location.href = '#Url.Action("dor","Home")';
}
</script>
HomeVM:
public class HomeVM
{
public List<SelectListItem> Files { get; set; }
public string SelectedFileName { get; internal set; }
public List<string> DynamicAlgorithems { get; set; }
}
Homecontroller:
public void dor()
{
//some code
}
The problem: when the user choose some item from combobox it redirect me to blank page i.e to http://localhost:55354/Home/dor, but I only want to call the function named dor, not to go to blank page!.
what am I missing?
Related
window.location.href always redirect to a new page URL assigned to it. You should use jQuery.ajax() to call the action method when onchange method triggered and return desired result:
jQuery (inside $(document).ready())
$('#SelectedFileName').change(function() {
var selectedFileName = $(this).val();
$.ajax({
type: 'GET',
url: '#Url.Action("Dor", "Home")',
data: { fileName: selectedFileName },
success: function (result) {
// do something
}
});
});
Controller
[HttpGet]
public ActionResult Dor(string fileName)
{
// do something
}
Note: Make sure that action method argument has same name with assigned data passed from AJAX callback.

jqueryui autocomplete render HTML returned by server

I have a simple page with an input text-box. The text box is bound to jquery ui autocomplete that makes an AJAX call to the server. My server side code is an ASP.NET MVC site. The only difference I have as compared to most examples found over the Internet is that my Server side code returns a PartialView (html code) as results instead of JSON. I see the AJAX call happening and I see the HTML response in the AJAX success event as well.
My question is how do I bind this HTML data to show in the AutoComplete?
The code I have so far is:
$("#quick_search_text").autocomplete({
minLength: 3,
html: true,
autoFocus: true,
source: function (request, response) {
$.ajax({
type: "POST",
url: "serversideurl",
data: "{ 'SearchTerm': '" + request.term + "', 'SearchCategory': '" + $("#quick_search_category").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
},
success: function (data) {
//THIS IS WHERE MY HTML IS RETURNED FROM SERVER SIDE
//HOW DO I BIND THIS TO JQUERY UI AUTOCOMPLETE
}
});
},
select: function (event, ui) {
},
response: function (event, ui) {
console.log(ui);
console.log(event);
}
});
This works:
1) Create an action in your controller and set the RouteConfig to start this action
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
Create a view without any type of master page
Add this view model:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
Go to Manage Nuget Packages or PM Console and add to MVC 5 project - Typeahead.js for MVC 5 Models by Tim Wilson
Change the namespace for the added HtmlHelpers.cs to System.Web.Mvc.Html and rebuild
Add this class:
public class CasesNorm
{
public string SCN { get; set; }
}
Add these methods to your controller:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
credit goes to http://timdwilson.github.io/typeahead-mvc-model/

how to pass parameters to actionreuslt using jquery mvc 3 razor?

i am new in mvc3 razor my prob is :
i have this actionResult method that can receive variables from jquery method
why my variables comes NULL
csharp :
public ActionResult GetOrdersSP(int? StoreId, int? SupplierId)
{
bool count = false;
var model = _storeOrderService.GetStoreSuppOrders(StoreId, SupplierId);
if (model.Count() > 0)
{
count = true;
return Json(count, JsonRequestBehavior.AllowGet);
}
else
{
return Json(count, JsonRequestBehavior.AllowGet);
}
}
and this is my jquery
$.fn.GetCount = function (data) {
var storeid = $('#StoreId').val();
var Supplierid = $('#Supplierid').val();
if (ValidateCreateOrder('#StoreId', '#Supplierid')) {
alert(storeid);
alert(Supplierid);
$.ajax(
{
url: '<%: Url.Action("GetOrdersSP", "StoreOrder")%>',
type: 'json',
data: { StoreId: $('#StoreId').val(),
SupplierId: $('#SupplierId').val()
},
success: function (json) {
//should popup the modal
alert(true);
}
});
}
}
please note that the storeid and supplierid are displayed correctly in the alert
thanks
I think you need to convert your data to json and parse it on actionResult.
See this post Pass a parameter to a controller using jquery ajax

Returning Multiple partial views from single Controller action?

I need to update Multiple from an Ajax call , I am confused as in how to return these Multiple views from the Controller Action method.
You can only return one value from a function so you can't return multiple partials from one action method.
If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel.
E.g.
Your view model would look like:
public class ChartAndListViewModel
{
public List<ChartItem> ChartItems {get; set;};
public List<ListItem> ListItems {get; set;};
}
Then your controller action would be:
public ActionResult ChartList()
{
var model = new ChartAndListViewModel();
model.ChartItems = _db.getChartItems();
model.ListItems = _db.getListItems();
return View(model);
}
And finally your view would be:
#model Application.ViewModels.ChartAndListViewModel
<h2>Blah</h2>
#Html.RenderPartial("ChartPartialName", model.ChartItems);
#Html.RenderPartial("ListPartialName", model.ListItems);
There is a very good example here....
http://rhamesconsulting.com/2014/10/27/mvc-updating-multiple-partial-views-from-a-single-ajax-action/
Create a helper method to package up the partial view...
public static string RenderRazorViewToString(ControllerContext controllerContext,
string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
Create a controller action to bundle the multiple partial views....
[HttpPost]
public JsonResult GetResults(int someExampleInput)
{
MyResultsModel model = CalculateOutputData(someExampleInput);
var totalValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_TotalValues", model.TotalValuesModel);
var summaryValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_SummaryValues", model.SummaryValuesModel);
return Json(new { totalValuesPartialView, summaryValuesPartialView });
}
Each partial view can use its own model if required or can be bundled into the same model as in this example.
Then use an AJAX call to update all the sections in one go:
$('#getResults').on('click', function () {
$.ajax({
type: 'POST',
url: "/MyController/GetResults",
dataType: 'json',
data: {
someExampleInput: 10
},
success: function (result) {
if (result != null) {
$("#totalValuesPartialView").html(result.totalValuesPartialView);
$("#summaryValuesPartialView").html(result.summaryValuesPartialView);
} else {
alert('Error getting data.');
}
},
error: function () {
alert('Error getting data.');
}
});
});
If you want to use this method for a GET request, you need to remove the [HttpPost] decorator and add JsonRequestBehavior.AllowGet to the returned JsonResult:
return Json(new { totalValuesPartialView, summaryValuesPartialView }, JsonRequestBehavior.AllowGet);
Maybe this solution can help you:
http://www.codeproject.com/Tips/712187/Returning-More-Views-in-an-ASP-NET-MVC-Action

Resources