MVC4 how to pass value to Html.Partial in javascript? - 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

Related

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

Showing Popup Windows with MVC, JavaScript

I have a simple create form in MVC 4 and would like two submit functions: (1) Create and (2) Create & Print. Create is a normal Create action and works perfectly. Create & Print should save the object and then launch a popup browser window with data from the newly saved object. The original window needs to refresh to a blank Create form ready for another record.
What is the best way to approach this?
Below is an example that works in practice however I have the ID hardcoded in. Ideally, this ID will dynamically inherit from the object that was just saved and link there. Is JavaScript the best idea here or should (can) I launch the popup from the Controller?
<input type="submit" value="Create" />
<input type="submit"
value="Create & Print"
onclick="window.open('Print/f1ad6330-2978-4ea9-9116-65f861412260'
, 'PRINT'
, 'height=200,width=200');" />
Best option is to create another action which returns string (last-insert-id), post data to it through ajax and get last-insert-id back in javascript then you can use it to open new window.
Now suppose this is new controller action:
[HttpPost]
public string CreateAndPrint(Object obj)
{
// Save data here / insert record here
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = db.GetLastInsertId; // get last insert id from database
return lastInsertId;
}
}
Have a javascript function to post the data:
<script type="text/javascript">
function creteAndPrint() {
$.ajax(
{
url : "CreateAndPrint",
type: "POST",
data : $("#from1").serialize(),
success:function(data)
{
var lastInsId = data; // you will get last insert id here.
var secWin = window.open('Print/'+lastInsId
, 'PRINT'
, 'height=200,width=200');
secWin.focus();
}
});
}
</script>
And call this function only on create & print button:
<input type="submit" value="Create & Print" onclick="creteAndPrint();" />
Hope it works for you. Thank you.
Here I am editing my answer after your comment :)
Yes! you can call the same Create action for achieving the same which I explained above. But for that you have to make some changes in the your Create action:
public string Create(Object obj)
{
// Save data here / insert record here
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = db.GetLastInsertId; // get last insert id from database
return PartialView("_Create", lastInsertId);
}
return View();
}
Notice that when you call this action through AJAX it will return a partial view, which return just LAST_INSERT_ID as string. You just have create one simple partial view _Create to print last-insert-id.
Partial view will have only two lines:
#model string
#Model
This will print the last-inst-id which we have passed from controller action.
I ended up bypassing the form's default submit call to the Create method and just created two new methods. It's not ideal, but it works.
SOLUTION
Form:
#using (Html.BeginForm("Dummy", "Count", FormMethod.Post, new { id = "form1" }))
{
// My Form
// Note the Dummy controller which will just fall through and do nothing
}
Form Submit:
<input type="submit" value="Create & Print" onclick="createAndPrint();" />
<input type="submit" value="Create" onclick="createWithoutPrinting();" />
JavaScript:
<script type="text/javascript">
function createAndPrint() {
$.ajax(
{
url: "CreateAndPrint",
type: "POST",
data: $("#form1").serialize(),
success: function (data) {
var lastInsId = data; // you will get last insert id here.
var secWin = window.open('Print/' + lastInsId
, 'PRINT'
, 'height=450,width=230');
secWin.focus();
}
});
}
</script>
<script type="text/javascript">
function createWithoutPrinting() {
$.ajax(
{
url: "Create",
type: "POST",
data: $("#form1").serialize()
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Dummy(Count count)
{
return RedirectToAction("Create");
}
[HttpPost]
public string CreateAndPrint(Count count)
{
SaveCount(count);
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = count.Id.ToString();
return lastInsertId;
}
return "";
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Count count)
{
SaveCount(count);
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = count.Id.ToString();
return PartialView("_Create", lastInsertId);
}
return RedirectToAction("Create");
}

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');

call server-side function from client-side in mvc3

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

Using javascript to call controller method in MVC

Im trying to make a table row work as a link to another view in my mvc website. Instead of using the standard "Details" link provided by the auto generated table list, I would like to use the table row as a link to the "Details" view instead. So somehow I need to make the row work as a link. Each rom has a unique id that I need to pass on to the controller method. I have tried different solutions but noting happens when I press on the table row...
So far this is what I have:
<script type="text/javascript">
$(document).ready(function(){
$('#customers tr').click(function () {
var id = $(this).attr('id');
$.ajax({
url: "Customer/Details" + id,
succes: function () { }
});
})
})
</script>
My controller method:
public ActionResult Details(int id)
{
Customer model = new Customer();
model = this.dbEntities.Customers.Where(c => c.Customer_ID == id).Single();
return View(model);
}
Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"CustomerDetails",
"Customer/Details/{id}",
new { controller = "Customer", action = "Details", id = "" }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(#"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Here is what I would do:
<tr data-id='#SomeRazorDataId' class="MyAction">foo</tr>
And then:
$(document).ready(function(){
$('.MyAction').live("click",function () {
var id = $(this).attr('data-id');
window.location = "Customer/Details/" + id;
})
});
If you are using jQuery 1.7+, you should use the on() method rather than the live() method.
Good luck!
There is a typo in your code;
success:
//----^
A couple of things:
Add a slash (/) between the action and the parameter: url: "Customer/Details/" + id, otherwise, you'll invoke an Action called Details123, for example, which doesn't exist;
Make sure you have a configured route in your Global.asax to support the id, i.e., Customer/Details/{id}:
Like #undefined said, the name of the callback is success, not succes.
Your Global.asax should have something along these lines:
routes.MapRoute(
"CustomerDetails",
"Customer/Details/{id}",
new { controller = "Customer", action = "Details", id = ""}
);
I had this type of situation lately and opted to use the Ajax helper class:
#Ajax.ActionLink("Details", "Details",
new
{
id = Model.Id
}, null)
In this example it would assume that you want a link saying 'details' and you're already in the Customer controller.
Either way, look at the helper classes if all you want to do is fire a controller action from a link, gives you a bit more strong typing in terms of how to pass/handle the id value etc
The url that you have tried to call is invalid:
"Customer/Details" + id,
instead it should be "Customer/Details&id=" + id
(OR)
use 'data'
$.ajax({
url: "Customer/Details",
data:{id:id},
succes: function () { }
});

Categories