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');
Related
new kid on the block w/ASP MVC ... tryna get an Edit form going in a JavaScript dialog box.
my current plan of action:
Main view has the edit button which onClick grabs the record_id, and makes an ajax call to my Controller-Action passing the record_id as the param.
In the same view, I am using a partial "_EditApp" which has the tabs/dialog related code.
In the same onClick, I am loading up the tabs that I specify in _EditApp.
JS ..
$('.btn_edit_app').click(function () {
var app_to_edit = $(this).attr('id');
$.ajax({
url: '/Application/editApp',
contentType: 'application/html; charset=utf-8',
data: { app_id: app_to_edit},
type: 'GET',
dataType: 'html',
success: function (result) {},
});
$('#edit_tabs').tabs({ active: 0 });
$('#edit_dialog').dialog({ width: 700, height: 400 });
});
my Controller/Action
public ActionResult editApp(int app_id)
{
AppDBServer ads = new AppDBServer();
ads = findADS(app_id);
return View("_EditApplication", ads);
}
the problem ...
simply, I want to retrieve the record and populate the tabs and dialog box with the retrieved data fields. Hence passing the model to the EditApplication Partial.
The issue is I am using the same partial in my main view that I am in the controller action and not sure how to go about this ... Ideas, or even a newer approach to this would be A-OK.
Also, I aiming to have data retrieval handled by the Controller / Action.
Thank you, SOF fam!
I only wanted to comment but I can't since I have less than 50 reputation. Anyways, if I understand correctly you want to pull up some tabs after a an action call. I've had to something like this before. Here was my solution:
onclick of the button or row with the ID call an ActionResult.
Or use an Ajax Form:
#using (Ajax.BeginForm("GetTabs", "ControllerHere", new AjaxOptions() { LoadingElementId = "loading", UpdateTargetId = "targetdiv", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }))
{
#Html.Hidden("id", id)
....
Submit
}
Return a PartialView i.e. "_Tabs" and pass the model (id in this case).
`
public ActionResult GetTabs(string id)
{
....
//pass id or get model and pass model
return PartialView("_Tabs", id);
}
`
Within the _Tabs.cshtml call Html.RenderAction for each tab.
(I had set up tabs using bootstrap)
Html.RenderAction takes an action method name and you can pass parameters.
`#{Html.RenderAction("GetTab1",new {id = #id}) }
#{Html.RenderAction("GetTab2",new {id = #id}) }`
..etc
Each Action will return a partial view...
public ActionResult GetTab1(string id)
{
//get data
model = id lookup
return PartialView("_Tab1", model);
}
...etc
So now we have the _Tabs partial view rendering its own partial views each that can have their very own model.
And when the _Tabs partial is done rendering it will return the HTML to the target div on the main page and have the x number of tabs you have created in the _Tabs.cshtml.
I also was able to keep the current active tab selected with the following script:
<script>
$('#navtab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#navtab a[href="' + hash + '"]').tab('show');
</script>
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");
}
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
i have a script if the user select a thumbnail shows
the larger image and the id from my database.
Until this point its works very well
what i try to do now is when the user clicks on the
thumbnail, i want to show the data which are in my table.
how can i do that?
My database relationship:
in my database i have 2 tables which one has the primary key
and the other the foreign key.
when i select the thumbnail which are in the table with the
primary key, i want to show the data from my other table
which contains the foreign key.
My code:
Javascript:
function swap(image) {
document.getElementById("imagem-selec").src = image.href;
$("input[name='Id_Img']").val($(image).data("id"));
}
HTML to show the list of thummbnails:
#foreach (var p in ViewBag.Img)
{
<li>
<a href="~/Files/#p.Name" onclick="swap(this); return false;" data-id="#p.Id">
<img src="~/Files/#p.Name"/>
</a>
</li>
Html which receive the path
<div id="wrap">
<img id="i-selec" src=""/>
</div>
Any sugestions?
Thanks in advance
UDPATE MY CODE:
Script
function swap(image) {
var imageID = $(image).data("id");
$.ajax("/{Admin}/GetImageData",
{
data: JSON.stringify({ ID: imageID }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
// Add your content to DOM here:
// values in data.data1 etc...
values in data.De, data.Sc
}
error: function () {
alert("error!");
}
});
};
Controller:
public JsonResult GetImageData(int ID)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlDataAdapter sqlAdapt = new SqlDataAdapter
(#"SELECT C.* From Content C inner join Image B on C.ID_Img = B.Id WHERE C.Id=" + ID, cn);
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(sqlAdapt);
DataSet data = new DataSet();
sqlAdapt.Fill(data, "Content ");
cn.Close();
return Json(data);
}
}
It seems like there are two choices:
Load the data in the view and have it hidden, on page load, and have the click event simply show the data.
Have an AJAX call to get the data that you want on the click event, and add the data when the call returns.
I would personally go with the AJAX call, as it uses a little extra network overhead on the requests, but potentially saves a lot of useless data from being downloaded:
// Data model.
class ImageData
{
public int data1 { get; set; }
public string data2 { get; set; }
...
}
// Controller action. Data access abstracted out.
public JsonResult GetImageData(int ID)
{
ImageData data = DataAccess.GetImageData(ID);
return Json(data);
}
Your JavaScript might look something like:
function swap(image) {
var imageID = $(image).data("id");
$.ajax("/{YourControllerHere}/GetImageData",
{
data: JSON.stringify({ ID: imageID }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
// creating the element to add
var div = document.createElement("div");
div.setAttribute("id", imageID);
$(image).parent().append(div);
//adding the data here. do this for each data item?
$("#"+imageID).append(data.details.YOUR_PROPERTY_HERE);
}
error: function () {
alert("error!");
}
});
}
The success callback has a parameter named "data". This is a JavaScript object representation of the data you returned in the controller action JsonResult.
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();
}
}