Call action to render a partial View in a AjaxRequest - c#

How you doing? I hope its good.
I have a "View" called Create and another two "partial" "views", a view is used to render a bootstrap modal and other to render a table, when I do a post in this modal I must to update that table, but when the model state of the modal is invalid I must call his action, how can I do this? I tryed to use return PartialView("ModalProduto", model);

try something like this
function () {
$.ajax({
url: URL/PartialViewAction,
type: 'GET',
data: $(form1.).serialize(), // or make your objects for the partial
success: function (data) {
$("#placeforthepartialview_as_a_modal").html(data);
},
error: function (e, data) {
}
});
});

Related

How to not pop validations on partial view load?

I have a partial view which contains a list of elements, to which i add a new element without limit, but when i add a field. It pops the validation for all the other fields of the list.
For example if i leave a field empty and call the controller and get the partial view back, the required error is poped for that field.
How can i avoid this case and pop validations only if they were poped before the post?
The id=5 is just for test purposes
I have a call to the controller like this
public ActionResult AddDestination(List<Destination> model)
{
model.Add(new Destination(){id = 5});
return PartialView("_FieldDestination", model);
}
AJAX Call:
function addField(event) {
debugger;
event.preventDefault();
var model = $("#multipleDestinations:input").serialize();
$.ajax({
type: 'POST',
url: '#Url.Action("AddDestination", "Controller")',
data: model,
success: function (data) {
debugger;
$("#multipleDestinations").html(data);
}
, error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);}
});
}

Redirect from partial view to view with json data object

I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.

Using jquery to render html from an action within an area

I have a jquery click method that looks like this
<script type="text/javascript">
function clickView(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.ajax({
url: "/Jac/ViewCustomDetails",
data: { productId: dataItem.Id },
success: function (response) {
$("#details").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
document.write(xhr.responseText);
}
});
}
</script>
Basically this makes an AJAX call to my controller to render an action.
The action ViewCustomDetails, which is within JacController, and within an area looks like this:
public ActionResult ViewCustomDetails(int productId)
{
Detail model;
model = new Detail
{
Price = productId.ToString(),
Origin = productId.ToString()
};
return View(model);
}
When I click on my button that fires off the AJAX call, I am able to break into my action. however I get this error in my view
The view 'ViewCustomDetails' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Jac/ViewCustomDetails.aspx
~/Views/Jac/ViewCustomDetails.ascx
~/Views/Shared/ViewCustomDetails.aspx
~/Views/Shared/ViewCustomDetails.ascx
~/Views/Jac/ViewCustomDetails.cshtml
~/Views/Jac/ViewCustomDetails.vbhtml
~/Views/Shared/ViewCustomDetails.cshtml
~/Views/Shared/ViewCustomDetails.vbhtml
Obviously there's no such controller/action in my views folder as my controller is within an area.
How do I get it to reference the controller in my area?
It IS referencing your controller but the line return View(model); in your ViewCustomDetails method requires the existence of a View file, which would normally be called ViewCustomDetails.cshtml
This View file must take a model type of Detail
You might also need to JSONify the returning view.
I just had to add the area name into my URL in the jquery code as such
url: "/Dan/Jac/ViewCustomDetails",
instead of just
url: "/Jac/ViewCustomDetails",

Partial view not rendering through ajax call

I have a controller action which is getting called by JQuery ajax, and hopefully returniung the contents of "Results" to the requesting page.
So far I have...
Controller
public ActionResult DynCalc(resultsModel model){
...
//code that populates model - all working ok
...
if (Request.IsAjaxRequest())
{
return PartialView("results", model.Results);
}
else
{
return null; //Handle this later
}
}
This passes back a valid model.
Called from the javascript:
$.ajax({
url: "/Test/DynCalc",
type: "POST",
data: $("#frmResults").serialize(), //This part works
dataType: "html",
success: function (result) {
$('#resultsSection').html(result);
$('#hide_panel a').flash("#111", 1000);
}
});
Sucess is never hit. Hopefully somebody can just tell me i'm being daft and missing something obvious?
My partial view results is just a HTML page with javascript on it. If I just have the following
Hello world in my results view, then it works ok, with any script in, it doesn't
Am I on the right track? Should I be changing the type of return on the controller? Or using JSON?
I didn't post the contents of the results page, as It doesn't matter if it's a whole document or simply <b>hi</b> - it does the same thing.
Try to return just a View. Because your result in this case is a complete View (because the action result could be HTML, XML, JSON...whatever).
Use PartialView only as a way to render part of your View.
E.g. on your MasterPage you would like to "always" render user info: #RenderAction("UserInfoAction", "UserController")
var model= {
"PropertyName1":$("#txt1").val(),
"PropertyName1": $("#txt2").val(),
}
$.ajax({
type:"POST",
url: 'Url.Action("DynCalc","ControllerName")',
data: JSON.stringify(model),
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr)
{
alert("The result is : " + status + ": " + data);
},
error: function (xhr)
{
alert(xhr.responseText);
}
});

ASP .NET MVC3 ajax call same function from various pages

How can I call the same action using ajax from different pages?
type: 'POST',
url: 'Notification/GetRecentNotifications/'
I'm currently using the code above to call my action. It works for my application's home page, but when I change to other page, this doesn't work. Can anybody give me a solution? Thanks before.
Heres what I usually do to point to which controller & action to call within an ajax jquery call...
$.ajax({
type: "POST",
url: '#(Url.Action("Action", "Controller"))',
success: function (data) {
}
});
Use Url.Action() to build links
Put the code in a ajax.js file in your scripts directory then reference it in the pages where you need to use the methods in that file. Then, put any server side logic for your ajax calls in an AjaxController For example:
ajax.js
function foo() {
var model = { };
$.ajax({
url: '#Url.Action("Foo", "Ajax")',
type: "POST",
data: JSON.stringify(model),
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
}
AjaxController.cs
public class AjaxController : Controller
{
[HttpPost]
public JsonResult Foo(FooModel model)
{
string message = _ajaxService.Foo(model);
return Json(message);
}
}
In the example above _ajaxService is a service layer object that contains the logic to handle your ajax requests. Below is how to use the function in your view:
SomeView.cshtml
<script type="text/javascript" language="javascript" src="#Url.Content("~/Content/Scripts/ajax.js")"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#button').click(foo);
});
</script>
If there is additional logic to pass data to the ajax method that is reused, you should probably put it in a partial view and reference that from every view that needs it.

Categories