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
Related
I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?
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/
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 });
}
How can I return IEnumerable's values with using ajax. Here is my script:
$.ajax({
type: "get", url: "street", data: { a: value2 },
success: function (data) {
alert(data);
}
And here is my controller method:
[HttpGet]
public string street(string a)
{
EmlakServicesClient client = new EmlakServicesClient();
client.ClientCredentials.UserName.UserName = "service_test";
client.ClientCredentials.UserName.Password = "..";
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
Street[] list =client.GetStreet(Convert.ToInt32(a));
return ("" + list.FirstOrDefault().StreetName);
}
As you can see at top I get value but with First Value so how can I get these all values from IEnumarable?
You should use JSON:
return Json(list, JsonRequestBehavior.AllowGet);
You will need to change your action method to return ActionResult.
return the Collection as JSON
public ActionResult GetsomeItems(int someId)
{
var someCollection=GetListOfItemsFromSomeWhere(someId)
return Json(someCollection,JsonRequestBehaviour.AllowGet);
}
I tripped over this while doing a Google search on how to return JSON results using ASP.NET Web API 2. In case someone else is looking for the same solution, here is the solution that worked for me:
// GET: api/Users
public HttpResponseMessage Get()
{
var users = UserManager.Get(); // returns IEnumerable
return Request.CreateResponse(HttpStatusCode.OK, users);
}
You can learn more about HttpResponseMessage here.
I have a html input text field and a button.
I want to take user input value from that html text field by clicking that button and want to send that value (by AJAX) into a MVC3 Controller ( as like as a parameter of an ActionResult setValue() ) ?
An other thing i want to know that, how i can get a return value (that return by a ActionResult getValue() ) from a MVC3 Controller and set it in a html text field (by AJAX) ?
please help me with a good example, please. and sorry for my bad English. :)
Button click event
$(document).ready(function ()
{
$('#ButtonName').click(function ()
{
if ($('#YourHtmlTextBox').val() != '')
{
sendValueToController();
}
return false;
});
});
You call your ajax function like so:
function sendValueToController()
{
var yourValue = $('#YourHtmlTextBox').val();
$.ajax({
url: "/ControllerName/ActionName/",
data: { YourValue: yourValue },
cache: false,
type: "GET",
timeout: 10000,
dataType: "json",
success: function (result)
{
if (result.Success)
{ // this sets the value from the response
$('#SomeOtherHtmlTextBox').val(result.Result);
} else
{
$('#SomeOtherHtmlTextBox').val("Failed");
}
}
});
}
This is the action that is being called
public JsonResult ActionName(string YourValue)
{
...
return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet);
}