MVC: How to add extra data to my Ajax ActionResult - ajax

Is there a way I can add extra data to my Ajax ActionResult in MVC?
I want my controller to create a new PartialView and then add extra data to it which can then be picked up in the Ajax OnSuccess function.
I have tried passing back a Json result from the controller with my custom data in it and using that in the OnSuccess function, but then, because I was only passing back my custom data and no HTML, the Ajax UpdateTarget div now goes blank because Ajax fills the div with my Json result which is not HTML.
I would like a way for my controller to send back a PartialView so my UpdateTarget div gets updated, that also contains my own custom data which I can use in the OnSuccess function.
Any help would be appreciated.
Thanks
Mike

You can use the following method in your controller:
public string UpdateDivWithContent()
{
var yourModel = ... //make custom data to create your partial
return RenderPartialViewToString("YourPartialViewName", yourModel)
}
I put this method into basic controller:
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = ControllerContext.RouteData.GetRequiredString("action");
}
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Call this action from your view using manual ajax call, for example:
$.ajax({
url: '#(Url.Action("UpdateDivWithContent","YourControllerName")'
type: 'POST',
data: {
//some params to be passed to the controller
},
success: function (result) {
//result is an html string of your customized partial view
$("#yourDivId").html(result);
}
});

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'

asp.net mvc-4: What should receive an ajax call

I'm new to ASP.NET MVC(-4).
I want to make an Ajax call from my website using jquery and fill in a div on the page using the returned html. Since it is only a div I do not need a full html page with header and full body and stuff.
What should be on the receiving side?
Should it be a normal view, a partial view, some special type of resource or handler or some other magic?
You can use this With Post and Get operaitons
Script
$.ajax({
url: '#Url.Action("SomeView")',
type: 'GET',
cache: false,
data: { some_id: id},
success: function(result) {
$('#container').html(result);
}
});
Controller
public ActionResult SomeView(int some_id)
{
....
return PartialView();
}
View
<div id="container">
#Html.Partial("SomeViewPartial")
</div>
OR you can use AjaxActionLink
View
#Ajax.ActionLink("text", "action", "controller",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "container",
OnSuccess = "onSuccess",
})
Script
function onSuccess(result) {
alert(result.foo);
}
Controller
public ActionResult SomeView(int some_id)
{
return Json(new { foo = "bar" }, JsonRequestBehavior.AllowGet);
}
Also You can use Ajax.ActionLink to update only content page. with using this:
In ~/Views/ViewStart.cshtml:
#{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
Since it is only a div I do not need a full html page with header and full body and stuff
You want a PartialView
You can return a View which has the Layout property value set to null
public class UserController : Controller
{
public ActionResult GetUserInfo()
{
return View();
}
}
and in GetUserInfo.cshtml
#{
Layout=null;
}
<h2>This is the UserInfo View :)</h2>
And you can call it from any page by using jQuery ajax methods
$("#someDivId").load("#Url.Action("User","GetUserInfo")");
If you want the Same Action method to handle an Ajax call and a Normal GET request call, ( Return the partial view on Ajax, Return normal view on Normal Http GET request), You can use the Request.IsAjax property to determine that.
public ActionResult GetUserInfo()
{
if (Request.IsAjaxRequest)
{
return View("Partial/GetUserInfo.cshtml");
}
return View(); //returns the normal view.
}
Assuming you have the Partial View (view with Layout set to null) is presetnt in Views/YourControllerName/Partial folder

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