Using javascript to call controller method in MVC - javascript

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

Related

Updating a div based on a select event from KendoUI Widget

I have a KendoUI search bar that has a drop down of autocompleted items based on what I type. When I type into I get a drop down menu. When I click on an item in the drop downlist, I want two things to happen. One which works, and that is loading a partial view. But, the other thing deals with updating a div element that is also in that partial view.
The partial view
#{
ViewBag.Title = "Client";
}
<div id="update">#ViewBag.name</div>
<p id="ahhh"></p>
External Javascript function
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
alert("IT WORKED");
},
error: function (result) {
alert("FAILED");
}
})
}
In the HomeController there is a method called someStuf. I am sending that item that is clicked on the event into the someStuf method.
Now here are the two controller methods that I'm working with.
Secretary s = new Secretary();
public ActionResult Client()
{
ViewBag.name = s.Client;
return PartialView();
}
[HttpPost]
public JsonResult someStuf(String n)
{
s.Client = n;
return Json(n, JsonRequestBehavior.AllowGet);
}
So then I update a class with that value that was passed from javascript. I then add that new value to the viewbag for the partial view Client.
Sorry for the misleading variables. Client is a type of model. Then I always have a partial view that is called client.
When I try this. The ViewBag is not showing the result that I would like. I can get the client side to send to the server. But I can't get the server to send to the client.... I bet it's something simple. But I'm trying to understand this step so I can use the same method to update id and class elements.
<p class="CompanySearchBar">
#(Html.Kendo().AutoComplete()
.Name("companyComplete") //The name of the AutoComplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("company") //Specify which property of the Product to be used by the AutoComplete.
.BindTo(Model)
.Filter("contains")
.Placeholder("Company name")
.Events(e => { e.Select("onSelect"); })
)
</p>
The above code allows for a search bar with autocomplete. While typing for an item a drop down list shows up with results having the same substring. When clicking one of the results the onSelect method is activated.
you can give like this and on change event just assign a value using jquery like
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
$('#ahhh').text(result.NAME); //the object which you returns from the controller
},
error: function (result) {
alert("FAILED");
}
})
}
<label id=ahhh></label>

How to use Partials in ASP MVC when used with Javascript to call a Controller Action?

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>

Url action parameters using Ajax

I am trying to pass data from a view to a controller using parameters.
Now I am running a few difficulities. I am trying to pass those parameters once I select a row from a table and press on a button which has a onclick method to ShowTasks()
The C# controller:
[Route("/service/delivery/{id}/{shopdoccode}/{regdate}")]
public ActionResult Delivery(string id, string shopdoccode, string regdate)
{
//do stuf
}
The Javascript function when user clicks on button:
function ShowTasks() {
//Dear Stackoverflow > This works, this is for selecting a row in the table
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
var dcColumn = 0;
var rdColumn = 1;
var shopdoccodeColumn = 3;
//assigning name to the colomn value
var id = $selectedRow[0].children[dcColumn].innerText.trim();
var regdate = $selectedRow[0].children[rdColumn].innerText.trim();
var shopdoccode = $selectedRow[0].children[shopdoccodeColumn].innerText.trim();
//ajax
if (id && regdate && shopdoccode) {
$.ajax({
type: 'POST',
url: '#Url.Action("service", "delivery" ,new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
data: { id, regdate, shopdoccode },
success: function (data) {
if (data.success) {
console.log("Succes");
}
},
error: function (data) {
console.log("Error");
}
});
}
}
}
What have I done so far? Sitting for hours trying to find a way to give the parameters to my controller so I can invoke a SQL stored procedure.
Unforntunately I can not simply use a hidden form for this.
Also this was quite helpful:
Url.Action parameters?
#sleeyuen
Looks to me like your Url.Action has its parameters in the wrong order. Change it to:
url: '#Url.Action("delivery", "service", new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
Here's the appropriate overload that you want:
Action(String, String, Object) with actionName, controllerName, and routeValues, in that order.
You can not *.js or *.html file wrtie razor code.
#Url.Action(string actionName,string controllerName,object routeValues)
The above code can only be used *.cshtml file.
test with Url.RouteUrl instead of Url.Action

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