call server-side function from client-side in mvc3 - javascript

I have followed this post, but the only thing that works from my solution is the error message alert. :D
My js-ajax code:
$(document).ready(function () {
$('a').click(function (e) {
var data = { 'id': $(this).attr("id") };
var dataVal = JSON.stringify(data);
$.ajax({
type: "POST",
url: "#Url.Action("ActionName", "ControllerName")",
contentType: "application/json; charset=utf-8",
data: dataVal,
dataType: "json",
success: function (id) {
alert(data.d);
alert("yay! it works!");
},
error: function(id){
alert("haha, it doesn't work! Noob!");
}
});
return false;
});
});
It is located at the end of the body, so it loads after all the other html contents are rendered.
This is my call-back function in the controller:
[HttpPost]
public ActionResult Hello(string id)
{
return RedirectToAction(id);
}
and the HTML anchor tag:
Read more
So, what I want is, upon any click of an anchor tag link, this JS to be fired and calling the function from the server-side, passing to it the value of the id parameter, where the call-back function will do its job (which is to call some View, according to the given id).
Buuuuut, I am getting only "haha, it doesn't work! Noob!" alert message. :D Any suggestions ?
Update with some code
RedirectToAction is a method from the framework, that redirects to another action. In this case I redirect to an action that will call me a certain view, for example this one:
public ActionResult Media()
{
//do some stuff here
return View();
}

You have to modify you method
public ActionResult Media()
{
//do some stuff here
return View();
}
to something like
public JsonResult Media()
{
//do some stuff here
return Json(new
{
myData = RenderPartialViewToString("ViewName", optionalModel),
errorMessage = error
});
}
Add following method with reference to ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter()) {
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}

Related

Redirect to View(ActionResult) with complex object as paremeter from Javascript

I have to perform following operation.
On a button click from View1, do Ajax request and get complex object as return.
Pass this object to View2 as parameter.
Process the data sent from view1 in client side(inside $(window).load()).
Below is my code:
View1 :
var Url = baseUrl() + "/InteractiveReport/GetRatingProfitData/";
$.ajax({
type: "POST",
url: Url,
contentType: "application/json; charset=utf-8",
dataType: "html",
// dataType: "json",
data: JSON.stringify({ "Projects": SelectedProjectinfo }),
success: function (JsonData) {
debugger;
var w = window.open('about:blank');
w.document.open();
w.document.write(JsonData);
w.document.close();
},
error: function (retVal) {
alert("error:" + retVal.responseText);
}
});
InteractiveReportController :
public ActionResult RatingProfitReport(ProfitRatingInfoModel RatingProfitData)
{
return View("RatingProfitReport", RatingProfitData);
}
public ActionResult GetRatingProfitData(IRSelectedProjectInfoModel Projects)
{
ProfitRatingInfoModel RatingProfitData = new ProfitRatingInfoModel();
//GET RatingProfitData from Database
return RatingProfitReport(RatingProfitDataMdl);
//var jsonSerializer = new JavaScriptSerializer();
//string response = jsonSerializer.Serialize(RatingProfitDataMdl);
//return Json(response, JsonRequestBehavior.AllowGet);
}
View2 :
#using Enterprise_Dashboard.Models
#model ProfitRatingInfoModel
<script>
//Control not entering this section
$(document).ready(function () {
init_bind_rating_profit_table();
});
function init_bind_rating_profit_table()
{
debugger;
var RatingProfitData = #Model.ProfitRatingData;
alert(RatingProfitData[0].BU);
}
</script>
Is there any better way to redirect to different view from Ajax call with parameters.
from my View1, if i directly make Ajax call to View2, i cannot pass complex object as parameter, since its too big string.
Is there any way i can set RatingProfitDataMdl into Session or ViewBag or ViewData or anything else and i can access it in View2?
OR
Is there any way i can eliminate Ajax call on button click so button click on View1 will automatically call GetRatingProfitData and it internally redirects to RatingProfitReport with modal object parameter?
OR
Completely different approach available to handle this scenario?

event.preventDefault() and redirect asp mvc/jQuery

What am trying to do is to post on form submit to a action and catch response and that works fine.Problem is when RedirectToAction gets called, it just stays on that same view(it doesn't redirect),or in case model is not valid, it doesn't show model validation. So i guess the problem is with url, but how can I correct it?
jQuery
$("form").on("submit", function (e) {
e.preventDefault();
var form = $(this);
var formURL = form.attr("action");
$.ajax({
type: "POST",
url: formURL,
data: $(this).serialize(),
success: function (response) {
if (response !== null && response.success == false) {
alert(response.responseText);
}
}
});
});
c# asp mvc
public ActionResult Add(SomeModel model) {
if (ModelState.IsValid) {
if (true) {
return Json(new { success = false, responseText = "Some error" }, JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Details", new { id = id });
}
//gets called but it doesn't show validation.
return View(model);
}
public ActionResult Details(int id) {
//gets called but it doesn't show the view.
return view(model);
}
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.
What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:
success: function (response) {
$("#div").html(response);
}
On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.

How to use jQuery to reload Partial with new parameter

I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});

MVC4 how to pass value to Html.Partial in javascript?

MVC4, on the click on dropdown item javascript function is called in view's 'scripts' section. Function makes ajax call to controller action, Json data returned. I need to pass some returned values to Html.Partial() to render in . How to accomplish that? Those value "do not exist in the current context" for Html.Partial().
VIEW : MyView
<div>#Html.DropDownList("listId", list, new { onChange=showText() }</div>
<div id="divMyText" ></div>
#section scripts{
function showText()
{
var val1 = 1;
$.ajax({
type:"POST",
url: "/Home/MyAction",
data: {parm1:val1},
success: function (result){
renderMyView(result.id);
}
});
}
function renderMyView(id)
{
$('#divMyText').html('#Html.Partial("MyView", new MyViewModel (id))'); // id here is Not 'visible' for MyViewModel.
}
}
CONTROLLER actions:
public ActionResult MyAction(int parm1)
{
.......
return Json (myObject);
}
public ActionResult MyView (int id)
{
MyViewModel model = new MyViewModel(id);
return View(model);
}
How to pass id value to MyViewModel in Html.Partial statement ?
Thank you
you need to combine them on the controller side. Change my action to
public PartialViewResult MyAction (int id)
{
MyViewModel model = new MyViewModel(id);
return PartialView("PartialName", model);
}
then in your script instead of calling your render view function
$('#divMyText').html(result);
this will take the returned partial view with the tied model and put it into the div

asp.net mvc Render a Partial View with Java Script

I want to make a Partial view that displays data in a table.
I will have a Select element with the services to choose from.
When the user Selects a Service in the combobox I want to the call a partial view with the service Id number:
How can I do this?
Here is a action method which will render the partialView
//
// GET: /Service/ServiceStatusLogs/1
public ActionResult ServiceStatusLogs(int id)
{
var db = new EFServiceStatusHistoryRepository();
IList<ServiceStatusHistory> logs = db.GetAllStatusLogs(id);
return View("_ServiceStatusLogs", logs);
}
Here is the main action method which returns the page:
//
// GET: /Services/Status
public ActionResult Status()
{
IList<Service> services;
using (var db = new EFServiceRepository())
{
services = db.GetAll();
}
return View(services);
}
You can make use $.ajax functionality to achieve, check this :-
//Combo box change event
$("#comboboxName").change(function () {
//Get service Id
var serviceId = $("#comboboxName").val();
//Do ajax call
$.ajax({
type: 'GET',
url: "#Url.Content("/Service/ServiceStatusLogs/")",
data : {
Id:serviceId //Data need to pass as parameter
},
dataType: 'html', //dataType - html
success:function(result)
{
//Create a Div around the Partial View and fill the result
$('#partialViewContainerDiv').html(result);
}
});
});
Also you should return partial view instead of view
//
// GET: /Service/ServiceStatusLogs/1
public ActionResult ServiceStatusLogs(int id)
{
var db = new EFServiceStatusHistoryRepository();
IList<ServiceStatusHistory> logs = db.GetAllStatusLogs(id);
return PartialView("_ServiceStatusLogs", logs);
}
Try this:
public ActionResult ServiceStatusLogs( int id )
{
//Prepare your model
return PartialView( "UserDetails", model );
}
Any then use javascript(ajax) to load contents for an element of the DOM:
$('#user_content').load('/Service/ServiceStatusLogs');

Categories