Using jquery to render html from an action within an area - c#

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",

Related

MVC Controller Action Result method call works, But view page doesn't appears

My project contains a view. which contain few text boxes and a button.
Button click will send the all text box value to controller method.
$('#btnNext').click(function () {
var dataToPost =
{
FirstName: $('#txt_FirstName').val(), LastName: $('#txt_lastName').val(), Email: $('#txt_emailID').val(),
MobileNumber: $('#txt_mobileNumber').val(), AddressLine1: $('#txt_addressLine1').val(), AddressLine2: $('#txt_addressLine2').val(),
Nationality: $('#ddlCountry').val(), State: $('#ddlCountry').prop('selectedIndex'), City: $('#ddlCountry').val(),
GenderTypeID: $('#ddlGender').val(), Pincode: $('#txtPincode').val()
}
$.ajax({
url: "/Main/getCompetitorDetails",
data: dataToPost,
type: "POST",
success: function (e) {
debugger;
alert(e);
Which is perfectly calling the method "getCompetitorDetails" in Main Controller.
Then the method call is calling the Payment view
public ActionResult getCompetitorDetails(CompetitorInformation cI) => View("Payment");
public ActionResult Payment() => View();
But the view is not showing.
When debugging , After the method call, The next step it is going to the Payment.cshtml page. Here:
#{
Layout = null;
}
Then nothing happens.
I didn't set any layout page as of now.
So i made it to null.
AM i missing anything here?

Call action to render a partial View in a AjaxRequest

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

Transferring info from view to Controller

I'm working on an asp-mvc application and facing the following issue:
I have a model with simple properties plus one property which is a list of my custom object, and I render the Ienumerable property as mentioned here:
Passing IEnumerable property of model to controller post action- ASP MVC
In my view, I have a button that is supposed to add items to the ienumerable property of my model. Of Course, I don't want to lose already inserted data, so I need to pass the model to the corresponding action.
I've noticed that the model os transferred entirely only upon post. So, I did something like:
$(".addButton").click(function (event) {
event.preventDefault();
$("#FilterForm").submit();
#{ Session["fromAddFullItem"] = "true";}
return false;
});
And then in my controller, I do something like:
public ActionResult Index(FilterModel model)
{
if (Session["fromAddFullItem"].ToString() == "true")
{
Session["fromAddFullItem"] = "false";
return AddBlankItemTemplate(model);
}
I've read that assigning session in js is not recommended, but also tried TempData, and there the data was always null.
My problem is that Session["fromAddFullItem"] is always true, even when I come from another button. If I put breakpoint in addbtn click in line- Session["fromAddFullItem"] = "false";, and press the other button, I see that for some odd reason the mentioned breakpoint is hit, even though I haven't pressed the add button.
Any help? Maybe there is another way to achieve what I want. Currently, no matter which button I press (which posts the form), it comes as Session["fromAddFullItem"] = "false" and goes to action AddBlankItemTemplate. Thanks.
EDIT - AJAX POST
$(".addButton").click(function(event) {
event.preventDefault();
var modelData = JSON.stringify(window.Model);
$.ajax({
url: '#Url.Action("AddBlankItemTemplate")',
type: 'POST',
dataType: 'json',
data: modelData,
contentType: 'application/json; charset=utf-8',
});
return false;
});
and controller
public ActionResult AddBlankItemTemplate(string modelData)
EDIT 2:
$(".addButton").click(function (event) {
event.preventDefault();
$.ajax({
url: '#Url.Action("AddBlankItemTemplate")',
data: $("#FilterForm").serialize()
}).success(function(partialView) {
$('DetailsTemplates').append(partialView);
});
});
and Controller:
public ActionResult AddBlankItemTemplate(FilterModel model)
The line #{ Session["fromAddFullItem"] = "true";} is Razor code and will be run on page rendering and load regardless of where you put it in the page.
It's not client side code so won't wait for your js code to run. If you're trying to synchronise state between js and MVC have you looked into angularjs which could simplify these actions.

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.

How to call an MVC Action using only JavaScript?

I have this Kendo UI dropdownlist with a select event that is handled by a JavaScript function.
I need to call an action result from a controller that runs a LINQ query to populate a Kendo UI grid on my page. My problem is the only way I can find to handle this even is with JavaScript and I have been unable to figure out how to call my action result from my controller from the JavaScript event function.
This is what the DropDownList looks like...
#(Html.Kendo().DropDownList()
.Name("Options")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Policies Not Archived",
Value = "1"
},
new SelectListItem() {
Text = "View All Policies",
Value = "2"
},
new SelectListItem() {
Text = "Filter Policies",
Value = "3"
}
})
.Events(e =>
{
e.Select("select");
})
)
and my JavaScript event handler that needs to call the action result
function select(e) {
}
and depending on the selection an ActionResult like this,
public ActionResult ViewAllPolicies()
{
//mycode
}
see this post
var url = '#Url.Action("ViewAllPolicies","YourController")';
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });
in controller
public ActionResult ViewAllPolicies()
{
//Should return json format
}
url – this is the URL where request is sent. In my case there is
controller called contacts and it has action calles
ListPartiesByNameStart(). This action method takes parameter
nameStart (first letter of person or company). success – this is the
JavaScript function that handles retrieved data. You can write there
also anonymous function but I suggest you to use functions with names
because otherwise your code may get messy when functions grow. type –
this is the type of request. It is either GET or POST. I suggest you
to use POST because GET requests in JSON format are forbidden by
ASP.NET MVC by default (I will show you later how to turn on GET
requests to JSON returning actions). dataType – this is the data
format that is expected to be returned by server. If you don’t assign
it to value then returned result is handled as string. If you set it
to json then jQuery constructs you JavaScript object tree that
corresponds to JSON retrieved from server.
Instead of returning json, you can also return a PartialView and in the .done function grab an element and replace it with the results from the partial view. PartialView actions basically return a fragment of HTML, and so you can just stuff that anywhere you want on the page:
$.ajax({
url: urlToPartialViewAction,
type: 'POST',
dataType: 'JSON',
data: '123'
})
.done(function (result) {
$('#someDivPlaceholder').replaceWith(result);
});
You could have something like a link or grey div and wire up to it's click event and then call this, the link might say "View Receipt" and when you click it you call an action that returns a partial view with the receipt, and so when they click it the div/link is replaced with the result. Kind of like the "View More Comments" links you see on social sites.
Note that you can't have a partial view by itself, it must be called through an action
public PartialViewResult _GetReceipt(string id)
{
ReceiptViewModel vm = //query for receipt data
return PartialView(vm);//render partial view and return html fragment
}
Once the select function executes, you need to make an AJAX call back to your Controller. You can use jQuery.ajax() (a wrapper for the most common AJAX operations) in the select function,
function select(e) {
var url = '#Url.Action("ViewAllPolicies", "PolicyController")';
var selectedPolicy = $('#Options').val(); // The option selected
$.ajax({
url: url,
type: 'POST',
dataType: 'JSON',
data: selectedPolicy
})
.done(function (data) {
// Display the data back from you Controller
});
}
You can look at the Kendo site for more info on how the DropDownList works.

Categories