pass data from view to controller without refreshing the view - ajax

i have a script in my view which is:
$('.datepicker').datepicker
(
{ onSelect: function (dateText, inst) {
//pass dateText to my controller
});
</script>
my controller is like this:
public ActionResult Index()
{
string dateSelected = dateText; //read dateText here
if (DateTime.TryParse(dateSelected, out date))
{
date = Convert.ToDateTime(dateSelected);
var reservations = db.Reservations.Where(r => r.Date == date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations);
}
return View();
}
i want dateText to be passed to the controller without the current page being refreshed or reloaded. how to do that?
i tried forms earlier and on the onselect event of the datepicker, i automatically submit the form so the controller can accept it. but i do not want the current page to be refreshed or reloaded.
i just want to pass dateText to the controller without the user noticing the passing.. some sort of $.post i guess but i dont know how to implement it..
UPDATE: here is my try, what is wrong:
ok here is my script:
JSONstring = JSON.stringify(dateText);
$.post("/Home/Index", { jsonData: JSONstring });
here is my controller:
public ActionResult Index(string jsonData)
{
CacheClear();
string dateSelected = jsonData;
.....
//i tried to debug it, but no value of jsonData
}

i want dateText to be passed to the controller without the current
page being refreshed or reloaded. how to do that?
You could use AJAX.

use ajax and send all the variables or data in the ajax data string and provide the url of your controller for example
function add_to_cart(id , title, price,qty){
$.ajax({
type: "POST",
url: "your controller" + id ,
data: "&title=" + title + "&price=" + price +"&quantity=" + qty ,
complete: function(data) {
//alert("Item added to cart");
}
});
}

Related

mvc ajax return partial view with model get the value of model in the success

I have ajax that return partial view with strongly type
I want in the success to get the values of the model.
is it possible?
the code return:
return View("Test", Model);
in the ajax:
I want to get the model in the data varible
success: function (data) {
data.
}
Your Partial View would need to return JSON data for you to be able to access the data like that.
In your controller (I'm assuming this is a HTTPPost call):
return Json(new { id = 1, name = "Test" });
In your JS Ajax call:
success: function(data) {
alert(data.name); //alerts 'Test'
}
update
OK, if you want to have the Partial View returned and the model, you could return the View as you already are then convert the model to a JSON string to be accessed and used in JS in the View maybe? Here's a rough example...
so in Controller:
using System.Web.Script.Serialization;
...
var jsonstring = new JavaScriptSerializer().Serialize(Model);
...
ViewBag.JsonString = jsonString;
then in the Partial View:
#{
var jsonString = ViewBag.JsonString;
}
<script>
var data = JSON.parse("#jsonString");
alert(data.name); //alerts 'Test'
</script>
No, for that you need to return JsonResult back from controller action which would be like:
return Json(new {response = Model });
Now it ajax success, you can access the result from json object which is returned :
success: function (data) {
console.log(data);
}
Try this is Ajax form
OnSuccess = "ShowMessage()"
and script is
<script>
function ShowMessage() {
document.getElementById('info').value='YOUR_MESSAGE';
setTimeout(function () {
$("#info").hide();
}, 3000);
}
<script>
and Your Html tag should be like this
<div id="info"></div>

How to show the view of method in controller when data passed from ajax in ASP.NET MVC

I am developing MVC application.
I want pass the values from View to controller.
I have use ajax to pass the values from View to controller.
Now this data goes perfectly into method....
$(document).ready(function () {
$('#CheckOrder').click(function(){
PassData();
});
function PassData()
{
$.ajax({
url: '#Url.Action("ShowWHOrder", "Order")',
type: 'POST',
data: { OrderNo: #ViewBag.OrderNo, OrderTo : '#ViewBag.OrderTo' }
});
}
});
Here is the method... in below method all parameters comes properly.
[HttpPost]
public ActionResult ShowWHOrder(string OrderNo, string OrderTo)
{
ViewBag.OrderNo = OrderNo;
ViewBag.OrderTo = OrderTo;
return View();
}
Now, I have added the new view for this method.
But It doesn't redirect to new view, it remains on previous view only.
Is due to ajax ?
What option I have to show the new view ?
How can I implement this without ajax ?

I want to handle crud operations on single view in mvc3 with different buttons along with javascript in mvc3

I want to handle crud operations on single view in mvc3 with different buttons along with javascript in mvc3.
Actually i have a view with account code and description fields.
i want to add,edit and delete record into sql server 2008 r2 database by using wcf services.
i want to use javascript for client side scripting.
i want to call controller's method by javascript button click event.
Please tell me how i do it.
currently i have following javascript function.
$(document).ready(function () {
var today = new Date();
var dd = today.getDate();
$('#sve').click(function () {
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
return false;
});
});
below is my controller code for save button
[Authorize]
// [Authorize(Roles = "Administrators")]
[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Save")]
public ActionResult Save(AccntBD model)
{
CBSWCF.Account useInfo = new CBSWCF.Account();
if (ModelState.IsValid)
{
if (!model.IsAcCodeExist(model.AcCode))
{
string ObjUser = User.Identity.Name;
string ObjUid = string.Empty;
AcntEnt.AcCode = model.AcCode;
AcntEnt.Descrip = model.Descrip;
objSvc.ACodeSave2(AcntEnt);
}
else
{
ModelState.AddModelError("CustomError", "Account Code Already Exist");
}
}
else
{
ModelState.AddModelError("", "");
}
return View(model);
}
i use following code to use multiple buttons in single view.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}
now problem is that my save function is not hit from javascript and message not saved successfuly is shown to me.
can anyone plz help me
There is no need to add the MultiButton attribute to the controller action if you are submitting the form via JavaScript the MultiButtonAttribute was created for when you wish to map submit Buttons to specific controller actions and this is possible because when you submit a form via a submit button the submit button name attribute is added to the post body with a its submit button specific value eg
<input type="submit" name="ButtonName" value="ButtonOne"/> <!-- would post ButtonName=ButtonOne -->
<input type="submit" name="ButtonName" value="ButtonTwo"/> <!-- would post ButtonNAme=ButtonTwo -->
If you wish to submit a form via javascript that will be routed to a different action based on the submit button you will be required to add the Button name and value to the querystring of the request
url: '/Home/Save?ButtonName=ButtonOne'

call to controller to populate text box based on dropdownlistfor selection using Ajax

I have a dropdown and when I select an item from it, I want to pass on the selected value to a function in a controller, query the db and auto load a text box with query results.
How do I use Ajax to make that call to the controller when there is onclick() event on the dropdown?
My dropdown and textbox in my aspx page is:
<%: Html.DropDownListFor(model => model.ApplicationSegmentGuid, Model.ApplicationSegment)%>
<%: Html.TextAreaFor(model => model.EmailsSentTo, false, new { style = "width:500px; height:50px;" })%>
My function in controller is
public ActionResult AsyncFocalPoint(Nullable<Guid> ApplicationSegmentGuid)
{
string tempEmail = UnityHelper.Resolve<IUserDirectory>().EmailOf();
tempEmail = "subbulakshmi.kailasam#lyondellbasell.com" + tempEmail;
IList<string> EmailAddresses = new List<String>();
using (TSADRequestEntities context = UnityHelper.Resolve<TSADRequestEntities>())
{
EmailAddresses = context.FOCALPOINTs.Where(T => T.APPLICATIONSEGMENT.ItemGuid == ApplicationSegmentGuid && T.FlagActive)
.Select(T => T.Email).ToList();
}
foreach (string emailAddress in EmailAddresses)
tempEmail = tempEmail + ";" + emailAddress;
return Json(tempEmail, JsonRequestBehavior.AllowGet);
}
You could give your dropdown an id and url:
<%= Html.DropDownListFor(
model => model.ApplicationSegmentGuid,
Model.ApplicationSegment,
new { id = "myddl", data_url = Url.Action("AsyncFocalPoint") }
) %>
and then subscribe to the .change() event of the dropdown list unobtrusively and trigger the AJAX request:
$(function() {
$('#myddl').change(function() {
// get the selected value of the ddl
var value = $(this).val();
// get the url that the data-url attribute of the ddl
// is pointing to and which will be used to send the AJAX request to
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { applicationSegmentGuid: value },
success: function(result) {
// TODO: do something with the result returned by the server here
// for example if you wanted to show the results in your textarea
// you could do this (it might be a good idea to override the id
// of the textarea as well the same way we did with the ddl):
$('#EmailsSentTo').val(result);
}
});
});
});

ASP.NET MVC 3.0 Update element content/html of the form using Partial action and jQuery ajax

I have Partial A1 inside Partial A.
I need to render my Partial view A1 on button A1B click.
For that i have an partial view action with parameter type of model of Partial view A (because there is some dependencies on A)
public PartialViewResult A1Partial(A model)
{
//Getting my deserialized model here successfully
//doing changes in the model collections
return PartialView("A1Partial", model);
}
I have onclick function to call my A1Partial partial action:
$(document).ready(function () {
$("#A1B").click(function () {
dataString = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Controller/A1Partial",
data: dataString,
dataType: "json",
success: function (data) {
//not working here
$("#myDiv").html("");
$("#myDiv").html(data);
}
});
return false;
});
});
My call from jQuery ajax working correctly and dataString getting deserialized in controller without any issues.
But i am didn't get anything in $("#myDiv").append(data); looks like the html didn't came through.
What changes i need to made to make it work?
You indicate that you expect a JSON response type:
dataType: "json"
And yet you try to use it as if it was HTML:
$('#myDiv').append(data);
So remove this dataType: 'json' from the AJAX request and in the success callback the data variable will represent the HTML returned by the A1Partial.
You have to render the partial view on the server and then send the HTML result via Json like this:
public static class Renders
{
public static string RenderPartialView(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
In the controller:
public JsonResult A1Partial(A model)
{
//Getting my deserialized model here successfully
//doing changes in the model collections
return Json(new
{
Html = this.RenderPartialView("A1Partial", model)
}, JsonRequestBehavior.AllowGet);
}
Then in the JQuery code:
$("#myDiv").html(data.Html);

Resources