MVC Core ajax and return result is a view - ajax

MVC Core, NET 5, not razor pages.
On a view I have three select components (bootstrap-select). I populate them via ViewModel.
"Get request -> Controller -> return View(viewModel);"
What I want...
When I changed value in any select component I do a post request (ajax) to the same controller (other method) and return view with repopulated data.
"'Post request -> Controller -> return View(changedModel);"
As I understood when I did ajax request I should handle it result in success and other cases.
What I should to do to reload page with new data?
Is it possible to achive this with this approach?

Yes, this is possible and you do not need to reload the page, just append the returned html to wherever you want it.
$.ajax({
type: "POST",
url: {your_url},
dataType: "html",
success: function (html) {
$("#someDiv").html(html);
}
});

What I should to do to reload page with new data?
If the post action return the same view as the get action and you want to reload the whole page, I think there is no need to use ajax. You can just redirect to post action with a form submission. If the view returned by the post action is a partialview you want render to the current view, you can use it like that in #cwalvoort answer.

Based on advices of cwalvoort and mj1313
I did:
Render main page with partials. ViewModel transfered to a partial as a parameter
On main page I added eventListners to controls with JS.
When control changes - ajax request to backend happens Controller/GetPartialView
Result from ajax replace html in partial section
Programmatically show needed components, re-add eventListners
PS Really need to learn Blazor or UI Framework :)
Code samples:
// JS
document.addEventListener("DOMContentLoaded", function (event) {
BindSelectActions();
});
function BindSelectActions() {
$('#selectGroups').on('hidden.bs.select', DoPartialUpdate);
$('#selectCompanies').on('hidden.bs.select', DoPartialUpdate);
$('#selectPeriods').on('hidden.bs.select', DoPartialUpdate);
}
function DoPartialUpdate(e, clickedIndex, isSelected, previousValue) {
// ToDo: Implement common script with "CallBackend" function
$.ajax({
type: "POST",
url: 'https://localhost:44352/TestController/TestGetPartial',
// no data its a stub at the moment
// data: $('#form').serialize(),
success: function (data, textStatus) {
$("#testControls").html(data);
$('#selectGroups').selectpicker('show');
$('#selectCompanies').selectpicker('show');
$('#selectPeriods').selectpicker('show');
BindSelectActions();
}
});
}
// Controllers
[HttpGet]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public async Task<IActionResult> Main()
{
// ViewModel = _helper -> _mediator -> query -> context
return await Task.Run(() => View(new TestViewModel()));
}
[HttpPost]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult TestGetPartial(TestViewModel model)
{
// ViewModel = _helper -> _mediator -> query -> context
var result = new TestViewModel();
result.IsPageReload = "yes";
result.TestCollection = new string[] { "A", "B", "C" };
result.Companies = new List<SelectListItem> { new SelectListItem { Value = "999",
Text = "Test" } };
// ModelState.Clear();
return PartialView("_TestPartial", result);
}
// Main and partial views
#model TestViewModel
#{
ViewData["Title"] = "Test";
}
<div id="testControls">
#await Html.PartialAsync("_TestPartial", Model)
</div>
#section Scripts {
<script type="text/javascript" src="~/js/test.js" asp-append-version="true">
</script>
}
#model TestViewModel
<form>
<div class="d-flex flex-row justify-content-between mt-4">
<div><select id="selectGroups" asp-for="Groups" asp-items="Model.Groups"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Group"></select></div>
<div><select id="selectCompanies" asp-for="Companies" asp-items="Model.Companies"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Company"></select></div>
<div><select id="selectPeriods" asp-for="Periods" asp-items="Model.Periods"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Period"></select></div>
<div><button type="button" class="btn btn-outline-dark">Import</button></div>
</div>
</form>
<div>
#{
if (null != Model.TestCollection)
{
foreach (var item in Model.TestCollection)
{
<p>#item</p>
<br>
}
}
}
</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;
}

Calling multiple action methods (using ajax) and showing the result of last in a new tab

I have a form in which I need to call two action methods, one after the other. This is how the flow goes.
First I check if the prerequisite data is entered by the user. If not then I show a message that user needs to enter the data first.
If all the prerequisite data is entered, I call an action method which return data. If there is no data returned then I show a message "No data found" on the same page.
If data is returned then I call another action method present in a different controller, which returns a view with all the data, in a new tab.
The View:
#using (Ajax.BeginForm("Index", "OrderListItems", null, new AjaxOptions { OnBegin = "verifyRequiredData"}, new { #id = "formCreateOrderListReport", #target = "_blank" }))
{
//Contains controls and a button
}
The Script in this View:
function verifyRequiredData() {
if ($("#dtScheduledDate").val() == "") {
$('#dvValidationSummary').html("");
var errorMessage = "";
errorMessage = "<span>Please correct the following errors:</span><ul>";
errorMessage += "<li>Please enter Scheduled date</li>";
$('#dvValidationSummary').append(errorMessage);
$('#dvValidationSummary').removeClass('validation-summary-valid').addClass('validation-summary-errors');
return false;
}
else {
$('#dvValidationSummary').addClass('validation-summary-valid').removeClass('validation-summary-errors');
$('#dvValidationSummary').html("");
$.ajax({
type: "GET",
url: '#Url.Action("GetOrderListReport", "OrderList")',
data: {
ScheduledDate: $("#dtScheduledDate").val(),
Crews: $('#selAddCrewMembers').val(),
Priorities: $('#selPriority').val(),
ServiceTypes: $('#selServiceTypes').val(),
IsMeterInfoRequired: $('#chkPrintMeterInfo').val()
},
cache: false,
success: function (data) {
debugger;
if (data !== "No data found") {
//var newUrl = '#Url.Action("Index", "OrderListItems")';
//window.open(newUrl, '_blank');
return true;
} else {
//Show message "No data found"
return false;
}
}
});
return false;
}
}
The "GetOrderListReport" Action method in "OrderList" Controller:
public ActionResult GetOrderListReport(OrderListModel model)
{
var contract = new OrderReportDrilldownParamDataContract
{
ScheduledDate = model.ScheduledDate
//Setting other properties as well
};
var result = OrderDataModel.GetOrderList(contract);
if (string.IsNullOrWhiteSpace(result) || string.IsNullOrEmpty(result))
{
return Json("No data found", JsonRequestBehavior.AllowGet);
}
var deserializedData = SO.Core.ExtensionMethods.DeserializeObjectFromJson<OrderReportDrilldownDataContract>(result);
// send it to index method for list
TempData["DataContract"] = deserializedData;
return Json(deserializedData, JsonRequestBehavior.AllowGet);
}
The last action method present in OrderListItems Controller, the result of which needs to be shown in a new tab:
public ActionResult Index()
{
var deserializedData = TempData["DataContract"] as OrderReportDrilldownDataContract;
var model = new OrderListItemViewModel(deserializedData);
return View(model);
}
The problem is that I am not seeing this data in a new tab, although I have used #target = "_blank" in the Ajax.BeginForm. I have also tried to use window.open(newUrl, '_blank') as can be seen above. But still the result is not shown in a new tab.
Please assist as to where I am going wrong?
If you are using the Ajax.BeginForm you shouldn't also be doing an ajax post, as the unobtrusive ajax library will automatically perform an ajax post when submitting the form.
Also, if you use a view model with data annotation validations and client unobtrusive validations, then there would be no need for you to manually validate the data in the begin ajax callback as the form won't be submitted if any validation errors are found.
The only javascript code you need to add in this scenario is a piece of code for the ajax success callback. That will look as the one you currently have, but you need to take into account that opening in new tabs depends on the browser and user settings. It may even be considered as a pop-up by the browser and blocked, requiring the user intervention to allow them as in IE8. You can give it a try on this fiddle.
So this would be your model:
public class OrderListModel
{
[Required]
public DateTime ScheduledDate { get; set; }
//the other properties of the OrderListModel
}
The form will be posted using unobtrusive Ajax to the GetOrderListReport of the OrderList controller. On the sucess callback you will check for the response and when it is different from "No data found", you will then manually open the OrderListItems page on a new tab.
This would be your view:
#model someNamespace.OrderListModel
<script type="text/javascript">
function ViewOrderListItems(data){
debugger;
if (data !== "No data found") {
var newUrl = '#Url.Action("Index", "OrderListItems")';
//this will work or not depending on browser and user settings.
//passing _newtab may work in Firefox too.
window.open(newUrl, '_blank');
} else {
//Show message "No data found" somewhere in the current page
}
}
</script>
#using (Ajax.BeginForm("GetOrderListReport", "OrderList", null,
new AjaxOptions { OnSucces= "ViewOrderListItems"},
new { #id = "formCreateOrderListReport" }))
{
#Html.ValidationSummary(false)
//input and submit buttons
//for inputs, make sure to use the helpers like #Html.TextBoxFor(), #Html.CheckBoxFor(), etc
//so the unobtrusive validation attributes are added to your input elements.
//You may consider using #Html.ValidationMessageFor() so error messages are displayed next to the inputs instead in the validation summary
//Example:
<div>
#Html.LabelFor(m => m.ScheduledDate)
</div>
<div>
#Html.TextBoxFor(m => m.ScheduledDate, new {id = "dtScheduledDate"})
#Html.ValidationMessageFor(m => m.ScheduledDate)
</div>
<input type="submit" value="Get Report" />
}
With this in place, you should be able to post the data in the initial page using ajax. Then based on the response received you will open another window\tab (as mentioned, depending on browser and user settings this may be opened in a new window or even be blocked) with the second page content (OrderListItems).
Here's a skeleton of what I think you are trying to do. Note that window.open is a popup though and most user will have popups blocked.
<form id="formCreateOrderListReport">
<input type="text" vaule="testing" name="id" id="id"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$('#formCreateOrderListReport').on('submit', function (event) {
$.ajax({
type: "POST",
url: '/home/test',
data: { id: $('#id').val()},
cache: false
}).done(function () {
debugger;
alert("success");
var newUrl = '/home/contact';
window.open(newUrl, '_blank');
}).fail(function () {
debugger;
alert("error");
});
return false;
});
</script>
Scale down the app to get the UI flow that you want then work with data.

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

Can I Use PartialViewResult with PagedList and show it in a PartialView

Hi everyone I have a question, Can I use PagedList in a PartialViewResult Action and show the result in a PartialView?
Here is some code
Controller Code:
public PartialViewResult CargosPorProyecto(string id, int? page)
{
var cargos = db.Cargo.Include(i => i.Proyectos).Where(i => i.NumProyecto.Equals(id)).OrderByDescending(i => i.Fecha);
if (Request.HttpMethod != "GET")
{
page = 1;
}
var pageSize = 10;
var pageNumber = (page ?? 1);
var onePage = cargos.ToPagedList(pageNumber, pageSize);
return PartialView("ListaCargosParcial", ViewBag.OnePage = onePage);
}
In my PartialView i put this code to show the pagination
<div class="pagination-right">
<div class="span12">
<%: Html.PagedListPager((IPagedList)ViewBag.OnePage, page => Url.Action("CargosPorProyecto", new { page = page }), new PagedListRenderOptions { LinkToFirstPageFormat = "<< Primera", LinkToPreviousPageFormat = "< Anterior", LinkToNextPageFormat = "Siguiente >", LinkToLastPageFormat = "Ăšltima >>" })%>
</div>
</div>
And when i load the page that contains the partialview everything looks good, but when i click in Next ("Siguiente") doesn't load in my partial view.
I hope I explained clearly and thanks for the time.
Regards
You could use AJAX if you want to stay on the same page. For example if you are using jQuery you could subscribe to the click event of the pagination links and then trigger an AJAX request to the corresponding controller action and refresh the partial with the results returned:
$(function() {
$('.pagination-right a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
// refresh the contents of some container div for the partial
// make sure you use the correct selector here
$('#some_container_for_the_partial').html(result);
}
});
// cancel the default action which is a redirect
return false;
});
});

How to update DIV in _Layout.cshtml with message after Ajax form is submitted?

Currently I have a Razor View like this:
TotalPaymentsByMonthYear.cshtml
#model MyApp.Web.ViewModels.MyViewModel
#using (#Ajax.BeginForm("TotalPaymentsByMonthYear",
new { reportName = "CreateTotalPaymentsByMonthYearChart" },
new AjaxOptions { UpdateTargetId = "chartimage"}))
{
<div class="report">
// MyViewModel fields and validation messages...
<input type="submit" value="Generate" />
</div>
}
<div id="chartimage">
#Html.Partial("ValidationSummary")
</div>
I then display a PartialView that has a #Html.ValidationSummary() in case of validation errors.
ReportController.cs
public PartialViewResult TotalPaymentsByMonthYear(MyViewModel model,
string reportName)
{
if (!ModelState.IsValid)
{
return PartialView("ValidationSummary", model);
}
model.ReportName = reportName;
return PartialView("Chart", model);
}
What I'd like to do is: instead of displaying validation errors within this PartialView, I'm looking for a way of sending this validation error message to a DIV element that I have defined within the _Layout.cshtml file.
_Layout.cshtml
<div id="message">
</div>
#RenderBody()
I'd like to fill the content of this DIV asynchronously. Is this possible? How can I do that?
Personally I would throw Ajax.* helpers away and do it like this:
#model MyApp.Web.ViewModels.MyViewModel
<div id="message"></div>
#using (Html.BeginForm("TotalPaymentsByMonthYear", new { reportName = "CreateTotalPaymentsByMonthYearChart" }))
{
...
}
<div id="chartimage">
#Html.Partial("ValidationSummary")
</div>
Then I would use a custom HTTP response header to indicate that an error occurred:
public ActionResult TotalPaymentsByMonthYear(
MyViewModel model,
string reportName
)
{
if (!ModelState.IsValid)
{
Response.AppendHeader("error", "true");
return PartialView("ValidationSummary", model);
}
model.ReportName = reportName;
return PartialView("Chart", model);
}
and finally in a separate javascript file I would unobtrusively AJAXify this form and in the success callback based on the presence of this custom HTTP header I would inject the result in one part or another:
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result, textStatus, jqXHR) {
var error = jqXHR.getResponseHeader('error');
if (error != null) {
$('#message').html(result);
} else {
$('#chartimage').html(result);
}
}
});
return false;
});

Resources