How to show the view of method in controller when data passed from ajax in ASP.NET MVC - ajax

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 ?

Related

rendering partial view without refreshing the main view in MVC

I have a Main view like below
#model pjct.Models.Main_Model
#using (Html.BeginForm("main_view", "pjct", FormMethod.Post))
{
//main form details
#Html.Partial("partial_view", #Model.partial_model)
//main form details
}
When the form render for first time the partial view model will be blank..
In the main view there is a textbox..When its value got changed an ajax call will occurred and generate a model for partial view. I don't have an idea hw to pass that model to partial and render it without refreshing the main view.
Ajax call to create partial model
$("#services").on('change', '#code', function () {
($("#code").val() != '' && $("#code").val() != null);
{
var code = $("#code").val();
$.ajax({
type: "GET",
url: '../main/get_price',
data: { c_code: code },
success: function (data) {
if (data) {
}
}
});
}
});
public ActionResult get_price(string c_code)
{
//generate the model for partial view and need to call the same.
}
How can i achieve the same..I am new to this partial model and not getting an idea.

Redirect to partial view on another controller

I am new in asp.net mvc programming, please be gentle... :)
Please notice that the following views are all PARTIAL views! Methods are called through Ajax and redirect to partial views with lists, forms are posted through Ajax, etc. OK, here we go...
1st controller named AlertsController. One of the methods is ResolveAlert(Guid id) which returns RedirectToAction -> UnresolvedAlerts() which is just a list of unresolved alerts.
2nd contoller named FrontDeskController. One of the methods is CustomerDetails(Guid id) which lists the customer and alerts that he might have.
I want to be able to "Resolve an alert" (thus use the method of the 1st controller) but return to the page that I was before instead of going to the redirected page that the method returns.
I added a second parameter to the ResolveAlert() method which lists a returnUrl string. I manage to send the Url that I want it to redirect to but I get just the partial (not rendered inside the whole page as it should)...
Here's my ResolveAlert method on my AlertsController:
// Resolve Alert POST
[HttpPost]
public async Task<ActionResult> Resolve(AlertModel model, string redirectUrl)
{
await _AlertsService.ResolveAsync(model);
if (!string.IsNullOrWhiteSpace(redirectUrl))
return Redirect(redirectUrl);
return RedirectToAction("Unresolved");
}
...and here is my CustomerDetails() method on my FrontDeskController:
// Display Customer Alerts
public async Task<PartialViewResult> CustomerDetails(AttendanceModel model, Guid id)
{
var customer = await _CustomersService.ReadAsync(id);
ViewData["Customer"] = await _CustomersService.ReadCustomerExtendedAsync(id);
var alerts = await _AlertsService.ReadCustomerAlertsAsync(id);
ViewData["Alerts"] = alerts.Where(x => x.IsResolved == false).ToList();
return PartialView("_CustomerDetails", model);
}
The ResolveAlert() method of the first controller is called in two steps... 1st I call a modal from the CustomerDetails view:
function resolveAlert(alertId, customerId) {
var returnTo = '/FrontDesk/CustomerDetails/' + customerId;
$.ajax({
method: 'GET',
url: '/Alerts/Resolve/' + alertId,
data: {returnUrl : returnTo},
dataType: 'html'
}).then(function (html) {
$('#dialog-container').html(html);
showDialog();
});
}
...then on the modal I have:
#{
var data = Request.Params["returnUrl"];
}
#using (Ajax.BeginForm("Resolve", "Alerts", new { redirectUrl = data}, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "partial", OnSuccess = "hideDialog" }, new { id = "form", #class = "form-horizontal" }))
{ ..... textbox with some notes that I can post while resolving the alert ..... }
... and (finally) here is the final part at the bottom of my modal:
<script type="text/javascript">
$('#form').validate({
rules: {
AlertNotes: {
required: true
}
},
submitHandler: function (form) {
$.ajax({
url: $(form).attr("action"),
data: $(form).serialize(),
type: $(form).attr("method")
}).then(function (result) {
$("#partial").html(result);
hideDialog();
});
}
});
</script>
I think that in order for the returned partial to get rendered correctly inside its container I should be returning a RedirectToAction from the ResolveAlert() method but the problem is that it belongs on a different controller...
Is it possible to get this working somehow or should I just bite the bullet and forget about having those pages as partials, get rid of the Ajax calls and use normal Url.Action() links?
It was just a Javascript/Ajax bug in my code.... Please disregard the question...
For those wondering, I had 2 forms using the same id. JS died silently allowing the form to be posted normally and not through Ajax. It had me scratching my head for a while now. Too bad that web development tools and VS in particular can't snipe such errors and provide a meaningful hint to assist you in debugging...

How To Correctly Use the HTML.DropDownList with Ajax Calls for MVC

I populated a SelectList Programmatically using the SelectList Constructor (IEnumerable, String, String)
IEnumerable<Permission> ie_SelLstContentAvailPerms;
tmpLstPermissions = FilterAssignablePermissionsByRoleMgblty(p_iRoleId,vmRolePermAdmin.lstPermissionsSource);
//test Forcing Results in to IEnumerable format for Select list Constructor
ie_SelLstContentAvailPerms = tmpLstPermissions.ToList();
vmRolePermAdmin.selLstPermissionsSource = new SelectList(ie_SelLstContentAvailPerms, "PermissionId", "Name");
And I use the DropDownList structure :
#Html.DropDownList("ddlAssignedRolePermissions", (Model.selLstCurrentRolePermissions), null, new { #id = "ddlAssignedRolePermissions", #size = "5", #onchange = "ddlAssignedRolePermissionsEvent(this)" })
My previous use of this structure has an ajax call who's success method is returning the updated model ----but its main body(Postify to AssignPermission(iUserID))is doing the work to the viewmodel based upon the item selected in the drop down list
$.ajax({
url: "~/../../User/AssignPermission",
type: "POST",
data: $.postify({ "p_permId": optionSelectedPerm.value, "p_UserId": iUserId }),
cache: false,
success: function () {
ReloadUserPermissions();
},
error: function () {
// alert("FAIL"); //TODO ?
}
});
I was attempting to replicate this structure for a new page , but instead of using the success results method of the Ajax call I've been trying to return the updated model in the main ajax work.. if the above example were structured this way there would be no success function and the controller ActionResult method would return the updated model. This isnt working . I see the data (updated) in the view while debugging but it does not up date the view ...
Do I have to use the success function of the Ajax call in order to update the view?
<script type="text/javascript">
$(document).ready(function () {
var optionSelectedPerm;
var mvcTmpData_iCurrentRoleID;
});
function SelectedRole(p_lstRole) {
debugger;
mvcTmpData_iCurrentRoleID = $("#ddlSelectedRole").val();
$.ajax({
url: "~/../../AdminRoles/AdminRolePermissions",
type: "POST",
data: $.postify({ "p_nullRoleId": mvcTmpData_iCurrentRoleID }),
cache: false,
success: function () {
AjaxReloadRolePermissions();
},
error: function () {
},
});
function AjaxReloadRolePermissions() {
//alert("Current RoleID: " + mvcTmpData_iCurrentRoleID);
var url = '#Url.Action("ReloadRolePermissions", "AdminRoles", new { p_RoleId = "zReplaceRoleId" })';
window.location.href = url.replace('zReplaceRoleId', mvcTmpData_iCurrentRoleID);
}
}
</script>
Please note that in order to accomplish the first working scenario the controller method as cited in the Ajax call "AssignPermission" is an ActionResult of Type EmptyResult and marked [HttpPost] so basically it can do work and not worry about a real return. BUT !! the Success function of this same Ajax call allows me to update the view with the newly adjusted ViewModel....
My atempt to reproduce my original results is failing I see the model content but it doesnt render in the view
If anyone cares its pretty simple the Ajax function's main work cant call a controller action that updates the view. However the Ajax success call can assuredly call one of the controller's ActionResults to update the view and thereafter its related Partials in that view ,,,
the controller action in tha main part of the ajax call that DOES WORK needs to be marked EmptyResult & [HttpPost]
The controller action that really fires up an ActionResult to update your view ,, in my case, just returns the view and the newly modified model... and again note its called by the Success function of the previous cited ajax function The last code posting above pretty much covers it all

Accessing model data, from MVC3 partial view, in controller without passing it explicitly in the view

I have a MVC3 partial view that is called with a model.
#model SomeModel
The model have an Id parameter.
In the view I call #Html.Action("SomeMethod", "SomeController")
Is there any way to access the Id parameter in the SomeMethod ActionResult without passing it explicitly like this:
#Html.Action("SomeMethod", "SomeController", new {"Id" = Model.Id})
The problem is that I can not change the source code of the partial view. And I need the Id value. The Id is not used in the partial view so I can not access it via JavaScript.
Is the model passed to the HttpContext and is there any way to pass it?
EDIT: The thing is that I am developing a plugin for nopCommerce, like the ones that are offered by nop-templates. nopCommerce is an open source software and I can change the code, but the plugin will be shipped separately, so it is not recommended to make changes in nopCommerce views and the view that I am referring to is such.
When you can't change the sourcecode of the partial view, there is no way of getting to the id value in your controller. Its completely decoupled as thats one major point of the MVC pattern.
You have to explicitely pass it as a parameter to your action.
A dirty workaround might be to store that id somewhere in the Session.
In my project i fill my state drop down list by country id like this
in my view
i pass country id to my controller ActionResult like this
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "#Url.Content("~/City/State")",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
alert(data);
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
in my controller i have action
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
i think this will help you ....

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

Resources