jquery ajax call from asp.net mvc app - asp.net-mvc

I am trying to call an action from jQuery. The action should return true or false,
and based on the return value I will do something.
I have the following code.
$("#payment").click(function (e) {
if($("#deliverytime").attr("disabled")){
//something here...
}
else
{
var postcode=$('#Postcode').val();
var restId='<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid="+restId+"&&postcode="+postcode;
$.ajax({
type: "GET",
url: URL
}).done(function(msg) {
if(msg==true){
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
else{
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
});
}
});
The code is not working. It says 'msg' is not defined. Is this not the way I should do this using jQuery-ajax? What am I doing wrong?
EDIT:
Controller action
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(Boolean.FalseString, JsonRequestBehavior.AllowGet);
}
else
return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
}
Modified function
var postcode = $('#DeliveryInfo_Postcode').val();
var restId = '<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid=" + restId + "&&postcode=" + postcode;
$.ajax({
url: URL,
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
$('#commonMessage').html(data);
return false;
}
}
});
EDIT -2
<script>
$(document).ready(function () {
$("#checkout").click(function (e) {
getDeliveryInfo();
});
});
function getDeliveryInfo() {
var URL ="/Restaurant/DoesRestaurantDeliver/6/2259"
$.get(URL, function (data) {
alert(data.isValid);
});
}
</script>
<%using (Html.BeginForm())
{ %>
<input type="submit" name="submit" id="checkout"/>
<%} %>
The above code does not work. But If i put the 'checkout' button out side of the form like below, it works.
<%using (Html.BeginForm())
{ %>
<%} %>
<input type="submit" name="submit" id="checkout"/>

You can configure your ajax call like below.
I feel your ajax call having problems on .done(function(msg) {} area.
Try to set success: function (data) {} like below.
<script type="text/javascript">
$(function () {
var companyName = $("#companyname");
$.ajax({
url: "/Company/GetName",
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
companyName.html(data.companyName);
}
}
});
});
</script>
EDIT
Action method should looks like below (This is a sample.Adjust it according to your situation)
[HttpGet]
public JsonResult GetName(string term)
{
var result = Repository.GetName(term);
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT 2
I would use Anonymous object (isValid) (remember that JSON is a key/value pairs):
Action Method
[HttpGet]
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(new { isValid = false},JsonRequestBehavior.AllowGet);
}
else
return Json(new { isValid = true },JsonRequestBehavior.AllowGet);
}
And then inside the ajax method:
success: function(data) {
if (data.isValid) {
...
}
}
EDIT 3
Just change your button type as below.(since you're not sending any values from form)
<input type="button" name="submit" id="checkout"/>

Related

DHTMLX Scheduler with Registration Form

I am trying to display events in the dhtmlx scheduler and pass the clicked event id to another registration form (view). I can get the event_id but I have no clue how to pass the event_id to controller action. My sample code is below:
<h2>Appointment Calendar</h2>
#using (Html.BeginForm())
{
<div class="scheduler_container" style='height: 600px;'>
#Html.Raw(Model.Render())
</div>
}
<script>
scheduler.attachEvent("onClick", function (id, e) {
console.log(id);
//call controller method
$.ajax({
type: "POST",
url: "/Home/Registration",
data: { EventId: id },
// data: {EventId:$('#event_id').val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
window.location.href = "Registration/" + id;
},
error: function (response) {
}
});
//window.location.href = "Registration/" + id;
return true;
});
</script>
controller:
public ActionResult Registration(int? EventId) <- the EventId is null here
{
var Event = db.Appointments.Where(s => s.Id.Equals(EventId)).FirstOrDefault();
...
return View();
}

Get and Set Value in drop downdown in MVC4

I am a beginer ...I don't know how to use dropdown in MVC this....I have used it like this
In ItemMaster.cshtml
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
In Controller.cs
public ActionResult ItemMaster(Item model)
{
ObservableCollection<Item> ItemList = new ObservableCollection<Item>();
Item Item = new Models.Item();
ItemList = Item.GetItemList();
Item Product = new Item();
DataTable dtProduct = new DataTable();
dtProduct = Item.GetProductList();
IList<Item> MyList = new List<Item>();
foreach (DataRow mydataRow in dtProduct.Rows)
{
MyList.Add(new Item()
{
Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
Product_Name = mydataRow["Name"].ToString().Trim()
});
}
var ProductName = new SelectList(MyList, "Id", "Product_Name");
ViewData["ProductName"] = ProductName;
return View(ItemList);
}
I am using Item list to fill grid view.... And I am using view data to fill drop down list....It is working fine.... I don't know how to get selected value when Button is clicked.
Try this,
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
<input type="button" id="btnasd" value="Click"/>
Script
<script type="text/javascript">
$(document).ready(function () {
$("#btnasd").click(function () {
var Id = $("#ProductName").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: "Post",
data: { ProductNameId: Id },
success: function (result) {
$("#mygrid").html('');
$("#mygrid").append(result.Data);
}
});
});
});
</script>
Do following(for onchange event of DropDownList):
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-", new { onchange = "doFunction();" })
javascript:
<script type="text/javascript">
$(document).ready(function () {
doFunction();
});
function doFunction() {
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
}
</script>
Or On button click
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-")
<input type="button" id="btnSubmit" value="Submit"/>
script:
$('#btnSubmit').click(function(){
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
});
Ask me if you have any query.
Note: You can also use DropDownListFor for model binded dropdown.

How do I Show/Hide partial view based on result I get from service call using jQuery AJAX in MVC4?

I want to have a page where I can enter loan number then I will call a WCF get service to see if a loan number is valid. If loan# is valid, I want to show loan related data (partial view) on the same page.
Here is my main View:
#model LoanStatus.Web.Models.Validate
#{
ViewBag.Title = "Validate";
}
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
}
<script type="text/javascript">
jQuery(function ($) {
$("#txtssn").mask("9999");
});
function validateRequest() {
var $form = $('form');
if ($form.valid()) {
$.support.cors = true;
var lnkey = $('#txtlnkey').val();
$.ajax({
type: "GET",
url: "http://localhost:54662/Service1/ValidateRequest/" + encodeURIComponent(lnkey),
contentType: "application/json; charset=utf-8",
dataType: "json", //jsonp?
success: function (response) {
$('#Result').html('Loading....');
if (response.ValidateRequestResult.toString().toUpperCase() == 'TRUE') {
alert('validated');
} else {
alert('cannot validated' + response.ValidateRequestResult.toString().toUpperCase());
//$("#Result").hide();
}
$('#Result').html(response.ValidateRequestResult);
//alert(response.ValidateRequestResult.toString());
},
error: function (errormsg) {
alert("ERROR! \n" + JSON.stringify(errormsg));
}
});
//
} else {
$('#Result').html('Input Validation failed');
}
}
</script>
#using (Html.BeginForm()) {
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.LoanKey, new{})
#Html.TextBoxFor(m => m.LoanKey, new { #id = "txtlnkey" })
#Html.ValidationMessageFor(m => m.LoanKey)
</li>
</ol>
<input type="button" value="Get Status" onclick="javascript:validateRequest();" />
</fieldset>
}
<div id="Result">
#if (ViewBag.Validated)
{
#Html.Action("GetLoanInfo");
}
</div>
Below is my controller:
namespace LoanStatus.Web.Controllers
{
public class ValidateController : Controller
{
//
// GET: /Validate/
[HttpGet]
public ActionResult Index()
{
var model = new Validate() {LoanKey = "", Last4Ssn = ""};
ViewBag.Validated = false;
return View(model);
}
[HttpPost]
public ActionResult Index(Validate model, bool validated)
{
// do login stuff
ViewBag.Loankey = model.LoanKey;
ViewBag.Validated = true;
return View(model);
}
public ActionResult GetLoanInfo() // SHOWs Search REsult
{
return PartialView("_LoanInfoPartial", ViewBag.Loankey);
}
}
}
I want to have '#Html.Action("GetLoanInfo");' rendered only if jQuery AJAX service call returns TRUE (Where I have alert('validated'). I am not sure how to do that. My issue can be resolved if I can set value to ViewBag.Validated in success:function(). But based on what I read, it cannot be set in jQuery.
I tried $("#Result").hide(); and $("#Result").show(); but it did not work. Please help.
Can you try with this:
In your function validateRequest() ajax success, at the place where you are showing alert('validated'); use this and try:
$('#Result').load('#Url.Action("GetLoanInfo", "Validate")');
In your view make Result div empty
<div id="Result"> </div>
Tell me if it helps.

ASP.NET MVC jquery checkboxlist post?

post methot:
function PostChartValues(meter_id, range_type_id, start_date, end_date) {
var values = $("#type_selection").val();
//values = expected values as string array
$.ajax({
url: '/Widget/GetMeterReadingsTimeSeries',
type: 'POST',
data: { MeterType: meter_id, DateRangeType: range_type_id, StartDate: start_date, EndDate: end_date, Parameters: values },
beforeSend: function () {
$("#chart_loading_div").show();
},
complete: function () {
$("#chart_loading_div").fadeOut();
$(".grids").jqGrid('GridUnload');
grid(meter_id, range_type_id, $("#start_date").val(), $("#end_date").val());
},
success: function (result) {
$("#chart").html(result);
},
error: function (result) {
alert("Seçilen kritere uygun veri bulunamadı!");
}
}); //end ajax
} //end PostChartValues
action method:
public ActionResult GetMeterReadingsTimeSeries(int MeterType, int DateRangeType, DateTime? StartDate, DateTime? EndDate,string[] Parameters)
{
// ...
return PartialView("_TimeSeries", chart);
}
I debugged it. only Parameters array is null. Is there an other way to post array with jquery post?
Thanks.
You can post selected values as string then you parse it back to array. I have created basic sample below,
Markup
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#someButton').click(function () {
var selectedValues = [];
$('#MyDiv input:checked').each(function () {
selectedValues.push($(this).val());
});
console.log(selectedValues);
$.ajax({
url: 'someurl',
type: 'POST',
data: { values: selectedValues.join(",") }
});
});
});
</script>
<button id="someButton">Do Ajax</button>
<div id="MyDiv">
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
</div>
Controller
public class HomeController : Controller
{
public void Test(string values)
{
string[] selectedValues = values.Split(',');
}
}
An alternate way to get the selected values if you're using Underscore:
var selectedValues = _.map($("#myDiv:checked"), function (item) { return $(item).val(); });

Rendering image(stream object) using jquery

Just wondering, how can I bind an image (stream) returned by an action method in an ajax call to an image element using jquery.
JavaScript:
$(document).ready($(function () {
$(':input').change(function () {
// object
var Person = {
Name: 'Scott',
Address: 'Redmond'
};
// Function for invoking the action method and binding the stream back
ShowImage(Person);
});
}));
function ShowImage(Person) {
$.ajax({
url: '/Person/GetPersonImage',
type: "Post",
data: JSON.stringify(Person),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
// idImgPerson is the id of the image tag
$('#idImgPerson')
.attr("src", data);
},
error: function () {
alert('Error');
}
});
Action method:
public FileContentResult GetPersonImage(Person person)
{
// Get the image
byte[] myByte = SomeCompnent.GetPersonImage(person);
return File(myByte, "image/png");
}
Problem:
The Action method is returning the stream, but it is not getting rendered on the page.
I am I missing some thing here...
Thanks for looking in to it.
So I was working on this today and ran into your question, which helped (and hurt) me. Here is what I found:
Like Eben mentioned you cant have the json data type. but thats only part of the problem. When you try to $('#idImgPerson').attr("src", data); as in your code you will just set the src attribute to the bytes returned by the call do the GetPersonImage() method.
I ended up using a partial view:
Using the standard mvc3 template
Index.cshtml (excerpt):
<h3>Using jquery ajax with partial views</h3>
<div id="JqueryAjax">
<input class="myButton" data-url='#Url.Action("GetImagesPartial","Home")' name="Button1" type="button" value="button" />
Create the partial view which makes reference to the action that provides the image:
#model string
<div>
<img id="penguinsImgActionJquery" alt="Image Missing" width="100" height="100"
src="#Url.Action("GetPersonImage", "Home", new { someString=Model })" />
<br />
<label>#Model</label>
</div>
HomeController with both action methods:
public ActionResult GetImagesPartial(string someImageName)
{
return PartialView((object)someImageName);
}
public FileContentResult GetPersonImage(string someString)
{
var file = System.Web.HttpContext.Current.Server.MapPath(localImagesPath + "Penguins.jpg");
var finfo = new FileInfo(file);
byte[] myByte = Utilities.FileManagement.FileManager.GetByteArrayFromFile(finfo);
return File(myByte, "image/png");
}
Jquery:
$(document).ready(function () {
$('.myButton').click(function (e) {
var bleh = $(this).attr("data-url");
e.preventDefault();
someData.runAjaxGet(bleh);
});
var someData = {
someValue: "value",
counter: 1,
};
someData.runAjaxGet = function (url) {
_someData = this;
$.ajax({
url: url,
type: "Get",
data: { someImageName: "ImageFromJQueryAjaxName" + _someData.counter },
success: function (data) {
$('#JqueryAjax').append(data);
_someData.counter = _someData.counter + 1;
},
error: function (req, status) {
alert(req.readyState + " " + req.status + " " + req.responseText);
}
});
};
});
sorry I know there is a little bit of extra code in the script file i was trying to play with namespaces too. Anyhow, i guess the idea is you request the partial view with ajax, which contains the image rather than requesting the image directly.

Resources