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

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>

Related

What to return after Ajax call asp.net

After ajax call is completed and the model is posted successfully to the controller, what should the controller return?
In my case, I just want to add an item to the wishlist and that's it, no redirect.
Controller can return a message or somethingelse for sure that your action did successful
This question you need to know two points, 1.What type can asp.net core return? 2.What type can ajax can receive.
First, Asp.net core can return the following types: Specific type, IActionResult, ActionResult<T>, Learn more details in this document.
Second, Ajax can send and receive information in various formats, including JSON, XML, HTML, and text files.
From your question, I think you want to recive the model from controller and add it to the wishlist in the view. So, In my opinion, You can directly return the specified model, Asp.net core will serialize models to Json Automatically. Then you can use it in your ajax success method.
simple demo:
<div class="text-center" id="Test">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
<button onclick="GetDetails(2)">submit</button>
#section Scripts{
<script>
function GetDetails(id){
var postData = {
'ProductId': id,
};
$.ajax({
type: "Post",
url: "/Home/privacy",
data: postData,
success: function (res) {
document.getElementById("Test").innerHTML = res["name"];
}
});
}
</script>
}
Controller
List<Student> students = new List<Student>()
{
new Student()
{
Id="1",
Name="Jack",
Country="USA"
},
new Student()
{
Id="2",
Name="Nacy",
Country="Uk"
},
new Student()
{
Id="3",
Name="Lily",
Country="Cn"
}
};
[HttpPost]
public Student Privacy(string ProductId)
{
var result = students.Where(x => x.Id == ProductId).FirstOrDefault();
return result;
}

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

Dynamically load Partial Views

How can i dynamically load a Partial View?
I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.
Use jQuery's $.load() with a controller action that returns a partial view.
For example:
HTML
<script type="text/javascript">
$(document).ready(function()
{
$("#yourselect").onchange(function()
{
// Home is your controller, Index is your action name
$("#yourdiv").load("#Url.Action("Index","Home")", { 'id' : '123' },
function (response, status, xhr)
{
if (status == "error")
{
alert("An error occurred while loading the results.");
}
});
});
});
</script>
<div id="yourdiv">
</div>
Controller
public virtual ActionResult Index(string id)
{
var myModel = GetSomeData();
return Partial(myModel);
}
View
#model IEnumerable<YourObjects>
#if (Model == null || Model.Count() == 0)
{
<p>No results found</p>
}
else
{
<ul>
#foreach (YourObjects myobject in Model)
{
<li>#myObject.Name</li>
}
</ul>
}
You can do this by following these steps. In your controller, you return a partial view.
[HttpGet]
public virtual ActionResult LoadPartialViewDynamically()
{
var query = _repository.GetQuery();
return PartialView("_PartialViewName", query);
}
then in the view you have an empty div
<div id="partialgoeshere"></div>
and then load the partial view using jQuery:
function LoadPartialView() {
$.get("#Url.Action(MVC.ControllerName.LoadPartialViewDynamically())", { null }, function (data) {
$("#partialgoeshere").empty();
$("#partialgoeshere").html(data);
});
}
Hope this helps
I believe you can do something like this example, just using the change event on your dropdown instead. It's a simple jQuery call, you can find more on the jQuery website.
$("#dropdown").change(function() {
$("#destination").load("/Products/GetProduct", $(this).val(),
function(result) {
// do what you need to do
});
});
The first parameter is the view you need to call for the details.
The second parameter is the selected value.
The third parameter of the $.load function is the callback function, where you can parse the result and do what you need to do.
If you have a multiple select $(this).val() that will give you an array with the selected options.
If you want only return a Json object you may want to follow this example.
Use Ajax :)
http://api.jquery.com/jQuery.ajax/
Example:
$.post(window.gRootPath + "Customer/PartialView", { Question: questionId})
.done(function (data) {
$('#partialDiv').html(data.responceText);
});
You can use ajax to call action an then just insert html string using jQuery to the page where you want it to appear:
Server-side:
Render partial view to string
Renders partial view on server to html string, useful when you need to add partial view to ASP.NET MVC page via AJAX.
Client-side:
$('#yourDdl').change(function()
{
$.get('/InsertPartialViewUsingAjax', function (data)
{
$('#container').html(data);
});
});
The following article tells you how to do it with minimum javascript. Basically you return html instead of JSON to your response object.
https://www.simple-talk.com/content/article.aspx?article=2118

pass data from view to controller without refreshing the view

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

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