Filling HTML Table with Dropwdownlists Change event in MVC - c#

I was trying to implement change event equivalent in MVC dropdownlist where it will fill the table below with relavant data from database.
But my Ajax call is not hitting the controller action method. can anybody tell me where I am mistaken
View and vavascript
#model WebArtSampler.Models.AssignRequestModel
#{
ViewBag.Title = "AssignRequest";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AssignRequest</h2>
#using (Html.BeginForm("AssignRequestNew", "SamCutAssignmentMasters"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CutAssignID)
<div class="form-group">
#Html.LabelFor(model => model.CutAssignID, "Cutting Request #", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.CutAssignID, (SelectList)ViewBag.CutAssignID, "--Select One--", htmlAttributes: new { #class = "form-control" })*#
#Html.DropDownList("Id", (SelectList)ViewBag.CutAssignID, htmlAttributes: new { #class = "form-control" })
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<div id="div1">
<table class="table">
<tr>
<th>
Req#
</th>
<th>
Buyer
</th>
<th>
Pattern Ref#
</th>
<th>
Style
</th>
<th>
Style Description
</th>
<th>
Fabric
</th>
</tr>
#foreach (var student in Model.Reqnumlist)
{
<tr>
<td>
#student.ReqNum
</td>
<td>
#student.BuyerName
</td>
<td>
#student.PatterRefNum
</td>
<td>
#student.StyleName
</td>
<td>
#student.StyleDescription
</td>
<td>
#student.Fabric
</td>
</tr>
}
</table>
</div>
JQuery I used is
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#Id").change(function () {
debugger
var Id = $(this).find('option:selected').val();
$.ajax({
url: "#Url.Action("PopulateDetails","SamCutAssignmentMasters")",
type: 'Get',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: { 'Id': Id },
success: function (data) {
if (data.success) {
debugger
document.getElementById("ProductName").value = data.productName;
}
else {
alert('invalid ID' + data.success);
}
}
});
});
});
</script>
Model
public class SamCutAssignmentMastersController : Controller
{
[HttpGet]
public JsonResult PopulateDetails(int id)
{
return Json(GetDetailsofaspecificTicket(id));
}
}

Firstly, check the specification for UrlHelper.Action, you're trying to use this overload:
public virtual string Action(
string actionName,
string controllerName
)
You have the action and controller names the wrong way round. In circumstances like this it's usually worth doing a "View source" on your code, you could have then seen that the url was incorrect.
Also you will need to update the syntax of your ajax call where you are passing the id parameter to:
data: { 'Id': Id },

Related

i am trying to have a create form and a list both working with ajax without refreshing page

i am working on an application. i am using two partial view in a single view. one of them is a create form for shortcode and the other one lists the shortcodes having a pagination.
this is my create form which is partial view
#model UniProject.Models.Short_Code
<div id="formDiv">
#using (Ajax.BeginForm("Create", "Service", new AjaxOptions { HttpMethod = "post" , UpdateTargetId = "formDiv" }))
{
<table>
<tr>
<td>#Html.LabelFor(model => model.ServiceCode)</td>
<td>#Html.TextBoxFor(model => model.ServiceCode , new { #class = "form-control input-sm"})</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.ServiceCode , "", new { #class = "text-danger"})</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Service)</td>
<td>
#Html.DropDownList("Service" ,new List<SelectListItem> {
new SelectListItem { Text = "Select" , Value = ""},
new SelectListItem { Text = "Package" , Value = "Package"},
new SelectListItem { Text = "Per-SMS" , Value = "Per-SMS"},
new SelectListItem { Text = "Barcode" , Value = "Barcode"}
}, new { #class = "form-control input-sm" })
</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.Service , "" , new { #class = "text-danger"})</td>
</tr>
<tr>
<td><input type="submit" value="Submit" class="btn btn-default btn-sm"/></td>
<td>#ViewBag.Record</td>
</tr>
</table>
}
this is my list which is also a partial view
#model IEnumerable<UniProject.Models.Short_Code>
<table class="table table-condensed table-bordered table-hover table-striped">
<tr>
<th>
Shortcode
</th>
<th>
Service
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ServiceCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Service)
</td>
</tr>
}
this is index view
#model PagedList.IPagedList<UniProject.Models.Short_Code>
#using PagedList.Mvc
<link type="text/css" rel="stylesheet" href="~/Content/PagedList.css" />
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Service Management</h3>
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"> </script>
<div class="col-lg-4">
#Html.Partial("_shortcode_form")
</div>
<div class="col-lg-8">
#Html.Partial("_shortcode_table")
</div>
<div id="pager">
#Html.PagedListPager(
Model ,
page => Url.Action(
"Index" ,
new {
page = page
}
)
)
</div>
<script>
$(function () {
$("#pager").on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cashe: false,
success: function (respons) {
$('#table').html(respond);
}
})
return false;
})
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
this is controller
public ActionResult Index(int? page)
{
var codes = db.Codes.AsQueryable();
codes = codes.OrderBy(c => c.Id);
if (Request.IsAjaxRequest())
{
return PartialView("_shortcode_table", codes.ToPagedList(pageNumber: page ?? 1, pageSize: 2));
}
return View(codes.ToPagedList(pageNumber: page ?? 1, pageSize: 2));
}
the problem is that when i pass this
codes.ToPagedList(pageNumber: page ?? 1, pageSize: 2)
to the view, this error generates
The model item passed into the dictionary is of type
'PagedList.PagedList`1[UniProject.Models.Short_Code]', but this
dictionary requires a model item of type
'UniProject.Models.Short_Code'.
please help how can is solve this issue. any help or assist would be welcome.

MVC Partial view using ajax

I have made an MVC application and I'm trying to create a partial view for when the user clicks the "details" button. I have one partial view working at the moment for my "delete" button. When I step through my code using breakpoints it brings me as far as my Task Controller and steps into my PartialViewResult method but then goes no further. When I click the "details" button nothing happens. Not sure what is missing here.
Index.cshtml
<span class="btn btn-success btn-sm" onclick="showTask('#item.TaskId')">Details</span>
<div id="Detail"></div>
<Script>
function showTask(showTaskID) {
$.ajax({
url: '#Url.Action("ShowTaskByID")',
data: { id: showTaskID },
success: function (data) {
$('#Detail').hide();
$('#Detail').html(data);
$('#Detail').animate({
opacity: 1,
left: "+=50",
height: "toggle"
}, 3000, function () {
// Animation complete.
});
$('#Edit').hide();
$('#Delete').hide();
},
error: function (data) { $('#Details').html('<h3>Error</h3>'); }
});
}
</script>
_ShowTask
#model IEnumerable<WebApplication4.Models.Task>
<div class="panel panel-info">
<div class="panel-heading" style="font-size:20px">
<h2>List of Actors</h2>
</div>
<p>
#Html.ActionLink("Create New Task", "CreateTask", null, new { #class = "btn btn-sm btn-primary" })
</p>
#if (Model.Any())
{
<table class="table table-condensed table-striped">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().TaskName)
</th>
<th>
#Html.DisplayNameFor(model => model.First().StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.First().FinishDate)
</th>
<th></th>
</tr>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.TaskName)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.FinishDate)
</td>
<td>
#Html.ActionLink("Edit", "EditTask", new { id = item.TaskId }, new { #class = "btn btn-info btn-xs" })
#*<a onclick="showEditActor('#item.MovieID','#item.ActorID','#item.ActorName','#item.age')" class="btn btn-xs btn-info">Edit</a>*#
#Html.ActionLink("Delete", "DeleteTask", new { id = item.TaskId }, new { #class = "btn btn-danger btn-xs" })
</td>
</tr>
}
} #* closing of if *#
</table>
}
else
{
<div><strong>No Actors in Movie</strong></div>
}
</div>
Task Controller
public ActionResult Details(int id)
{
var q = db.Tasks.Find(id);
if (q == null)
{
}
return View(q);
}
public PartialViewResult ShowTaskByID(int id)
{
return PartialView("_ShowTask", db.Tasks.Find(id).TaskName);
}
HTML
<input id="btnDetail" type="button" class="btn btn-success btn-sm" value="Details" />
<div id="Detail"></div>
JS
$('#btnDetail').on('click', function(){
$.ajax({
url: '#Url.Action("ShowTaskByID")',
data: { id: showTaskID },
}).done(function (data) {
$('#Detail').html(data);
$('#Detail').animate({
opacity: 1,
left: "+=50",
height: "toggle"
}, 3000, function () {
// Animation complete.
});
$('#Edit').hide();
$('#Delete').hide();
}).fail(function (jqXHR, textStatus) {
$('#Detail').html('<h3>Error :' + jqXHR.responseText + '</h3>');
});
});
C#
public ActionResult Details(int id)
{
try
{
var task = db.Tasks.Find(id);
}
catch(HttpException e)
{
throw new HttpException(404, "Task not found.")
}
return View(task);
}
public PartialViewResult ShowTaskByID(int id)
{
try
{
var tasks = db.Tasks.Find(id).TaskName;
}
catch(HttpException e)
{
throw new HttpException(404, "Task nout found.")
}
return PartialView("_ShowTask", tasks);
}
If you are expecting a list of Tasks try this:
public PartialViewResult ShowTaskByID()
{
try
{
var tasks = db.Tasks.ToList();
}
catch(HttpException e)
{
throw new HttpException(404, "Task nout found.")
}
return PartialView("_ShowTask", tasks);
}
Or instead, you could edit _ShowTask model type to Task:
#model WebApplication4.Models.Task
<div class="panel panel-info">
<div class="panel-heading" style="font-size:20px">
<h2>List of Actors</h2>
</div>
<p>
#Html.ActionLink("Create New Task", "CreateTask", null, new { #class = "btn btn-sm btn-primary" })
</p>
#if (Model.Any())
{
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.TaskName)
</th>
<th>
#Html.DisplayNameFor(model => model.StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.FinishDate)
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
#Html.DisplayFor(model => model.TaskName)
</td>
<td>
#Html.DisplayFor(model => model.StartDate)
</td>
<td>
#Html.DisplayFor(model => model.FinishDate)
</td>
<td>
#Html.ActionLink("Edit", "EditTask", new { id = Model.TaskId }, new { #class = "btn btn-info btn-xs" })
#*<a onclick="showEditActor('#item.MovieID','#item.ActorID','#item.ActorName','#item.age')" class="btn btn-xs btn-info">Edit</a>*#
#Html.ActionLink("Delete", "DeleteTask", new { id = Model.TaskId }, new { #class = "btn btn-danger btn-xs" })
</td>
</tr>
</tbody>
} #* closing of if *#
</table>
}
else
{
<div><strong>No Actors in Movie</strong></div>
}
</div>
[HttpGet]
add the tag to your public PartialViewResult ShowTaskByID(int id)
so, it should result like:
[HttpGet]
public PartialViewResult ShowTaskByID(int id)

Jquery $.ajax and load function cannot pass parameters to MVC controller to get partial view into modal dialog

Good time of the day, stack overflow community. I was building my first application with jquery ajax calls, but I'm having troubles with getting customer information, passed from controller action method as partial view to show it in a modal dialog.
When I use .load function it works as expected, but I cant pass any parameters to my controller action method. Then I tried to use $.ajax, but still no luck.
Let me post my code so you will have better idea of my problem.
My Main view
#model IEnumerable<App.AppService.Customer>
#{
ViewBag.Title = "GetCustomers";
}
<script type="text/javascript">
$(document).ready(function() {
var customerID = 0;
$("input[type=button]").click(function() {
customerID = this.id;
debugger;
$("#dialogDiv").dialog("open");
});
$(function() {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
open: function() {
$.ajax({
url: '#Url.Action("GetCustomer", "Customer")',
contentType: 'application/json; charset=utf-8',
method: "get",
data: JSON.stringify({ customerId : customerID }),
dataType: 'html'
});
},
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
});
</script>
<h2>GetCustomers</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="row">
<div class="col-md-offset-1 col-md-10">
<table class="table table-condensed table-striped">
<tr>
<th class="text-center">
#Html.DisplayNameFor(model => model.CustomerName)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.Company)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.Email)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr id="#item.CustomerID">
<td>
#Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Company)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>
<input type="button" value="edit" id="#item.CustomerID" /> |
#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID })
</td>
</tr>
}
</table>
</div>
</div>
<div id="dialogDiv" title="Edit customer">
<h3>Please wait ...</h3>
</div>
In this view I retrieve all the customers and when edit button is clicked I want to call controller method and retrieve customer by his id in modal dialog.
Below is my controller ActionMethod:
[HttpGet]
public ActionResult GetCustomer(int customerId)
{
Customer customer = repository.GetCustomerById(customerId);
return PartialView("_GetCustomerPartial", customer);
}
[HttpPost]
public ActionResult GetCustomer(Customer customer)
{
if (repository.UpdateCustomer(customer))
{
return RedirectToAction("GetCustomers");
}
return HttpNotFound();
}
And my Partial View:
#model App.AppService.Customer
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Company)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Company)
#Html.ValidationMessageFor(model => model.Company)
</div>
#Html.HiddenFor(model => model.CustomerID)
<div class="editor-label">
#Html.LabelFor(model => model.CustomerName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CustomerName)
#Html.ValidationMessageFor(model => model.CustomerName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
With this code I'm getting Null reference error. I believe it is because parameters are not passed to action method.
If I use just a load function without any parameters (just for testing), it works perfectly and returns customer object as a partial view to my modal dialog.
Working code:
$(document).ready(function () {
$("input[type=button]").click(function () {
var customerId = this.id;
debugger;
$("#dialogDiv").dialog("open");
});
$(function () {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
open: function () {
debugger;
$(this).load("#Url.Action("GetCustomer")");
},
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
});
With changes in controller action.
[HttpGet]
public ActionResult GetCustomer()
{
Customer customer = repository.GetCustomerById(any int id);
return PartialView("_GetCustomerPartial", customer);
}
I want to achieve same working functionality, but with parameters I can pass to controller action method.
I went through this post, but unfortunately didn't understand the solution people provided in comments.
Thank you in advance!
After continuously working on this issue I finally got it working. Below is the solution:
$("input[type=button]").click(function () {
var customerId = this.id;
$.ajax({
url: '#Url.Action("GetCustomer","Customer")',
contentType: 'application/json; charset=utf-8',
method: "get",
data: ({ customerId: customerId }),
dataType: 'html',
success: function (result) {
$("#dialogDiv").dialog("open").html(result);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$("#output").html(msg);
$("#output").css("visibility", "visible");
}
});
});
$(function () {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
Main points to mention here is that I was using $.ajax call in the wrong place, and removing JSON.stringify helped my to avoid null reference exception. As the return type from the action method was html and I just filled my dialog div with that html and everything worked like a charm.

MVC get details from partial view to show in textboxes

I have 3 views (1 Index, 2 Contacts(partialview), 3 Details(partialview))
I have a database with 2 tables tied by ContactId that i can use to get the Details from the database to show. I used ADO to make a model of the database. The 2 tables (classes) are named Contact and ContactTelefon.
Instead of button I tried using #html.ActionLink (as u can see in Contact View) to get the Id from the row, but that takes me to a new page, and it doesn't even show details.
My question is: How could i get the details to show in textboxes so i can edit the data.
All actions must be in same view as far as the user is concerned.
Controller:
ContactsDbEntities db = new ContactsDbEntities();
[HttpGet] //Index
public ActionResult Index()
{
return View();
}
//Contacts
public ViewResult Contacts()
{
var contactsList = db.Contacts.ToList();
return View(contactsList);
}
//Details
public ActionResult Details(int? id)
{
ContactTelefon contactTel = db.ContactTelefons.Find(id);
return View(contactTel);
}
Index view
#using Demo.Models
#model Contact
#section scripts
{
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script>
$(function () {
$(document).on('click', '#Details', function () {
$.get('#Url.Action("Details","Home")', function (data) {
$('#divDetails').replaceWith(data);
});
});
</script>
}
<table id="mainTable" class="table table-bordered table-striped">
<tr>
<th>
#Html.DisplayNameFor(model => model.ContactId)
</th>
<th>
#Html.DisplayNameFor(model => model.Nume)
</th>
<th>
#Html.DisplayNameFor(model => model.Prenume)
</th>
<th>
#Html.DisplayNameFor(model => model.Adresa)
</th>
<th>
#Html.DisplayNameFor(model => model.Mentiuni)
</th>
</tr>
<tr>
<th>
</th>
#using (Html.BeginForm())
{
<th>
#Html.TextBoxFor(model => model.Nume, null, new { id = "txtSearchNume", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Prenume, null, new { id = "txtSearchPrenume", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Adresa, null, new { id = "txtSearchAdresa", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Mentiuni, null, new { id = "txtSearchMentiuni", #class = "form-control" })
</th>
<th>
<input type="submit" value="Create" class="btn btn-success"
onclick=" location.href='#Url.Action("Index", "Home")' " />
</th>
<th>
<input type="submit" name="submitSearch" value="Search" class="btn btn-info"
onclick=" location.href='#Url.Action("Create", "Home")' " />
</th>
<tr>
#{Html.RenderAction("Contacts", "Home");}
</tr>
<tr><div id="divDetails"></div></tr>
}
</table>
Contacts View
#using Demo.Models
#model IEnumerable<Contact>
<table class="table table-bordered table-hover">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ContactId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nume)
</td>
<td>
#Html.DisplayFor(modelItem => item.Prenume)
</td>
<td>
#Html.DisplayFor(modelItem => item.Adresa)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mentiuni)
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.ContactId },
new { #class = "btn btn-danger", onclick = "return confirm('Delete this record?');" })
</td>
<td>
<input id="Details" type="button" name="Details"
value="Details" class="btn btn-info" />
</td>
<td>
#Html.ActionLink("DetailsLink","Details",new{id = item.ContactId})
</td>
</tr>
}
</table>
Details View
#using Demo.Models
#model ContactTelefon
<div class="form-horizontal">
<div claass="form-group">
#* must get the id from Contacts *#
#Html.LabelFor(model => model.ContactId)
#Html.LabelFor(model => model.ContactTelefonId)
#Html.LabelFor(model => model.NumarTelefon)
#Html.LabelFor(model => model.TipNumarTelefon)
</div>
<br />
<div claass="form-group">
#Html.DisplayFor(model => model.ContactId)
#Html.DisplayFor(model => model.ContactTelefonId)
#Html.DisplayFor(model => model.NumarTelefon)
#Html.DisplayFor(model => model.TipNumarTelefon)
</div>
<div claass="form-group">
#Html.EditorFor(model => model.ContactId)
#Html.EditorFor(model => model.ContactTelefonId)
#Html.EditorFor(model => model.NumarTelefon)
#Html.EditorFor(model => model.TipNumarTelefon)
</div>
</div>
It seems as if you're starting MVC coming from ASP.NET WebForms. The thing about MVC is that it doesn't do any magic like WebForms so you have to have a good understanding of what happens behind the scenes to be able to make a smooth transition. Also, from the looks of it your database model uses Entity Framework.
First off the way you're handling the Details button is all wrong. What you should be doing is this:
HTML
<input type="button" name="Details" value="Details" class="btn btn-info js-details"
data-id="#item.ContactId" />
JavaScript
$(document).on('click', '.js-details', function (event) {
// get the element that triggered the event
var $element = $(event.currentTarget);
var id = $element.data('id');
// you might have to type in the literal URL if you have a custom route
// here
$.get('#Url.Action("Details","Home")'+ '?id=' + id, function (data) {
$('#divDetails').html(data);
});
});
Let me know if this works for you. There are other things that you can improve but this should be a pretty good start.

how can i determine which dropdownlistfor caused postback in mvc3?

i have 2 dropdownlistfor in the view .. every one of them can cause postback
i want to get the name of the one when cause postback
<tr>
<td>
<label>
Owner</label>
</td>
<td>
#Html.DropDownListFor(m => m.OwnerId, new System.Web.Mvc.SelectList(Model.CallForPaperJournalOwnersList, "OwnerId", "Owner"), new { onchange = "submit();" })
</td>
</tr>
<tr>
<td>
<label>
Journal Code:</label>
</td>
<td>
#Html.DropDownListFor(m => m.JournalCode, new System.Web.Mvc.SelectList(Model.JournalsWithCallForPaperHtmlList, "JournalCode", "JournalCode"), new { onchange = "submit();" })
</td>
</tr>
in this case ... i would use an id :
<tr>
<td>
<label>
Owner</label>
</td>
<td>
#Html.DropDownListFor(m => m.OwnerId, new System.Web.Mvc.SelectList(Model.CallForPaperJournalOwnersList, "OwnerId", "Owner"), new { id = "btnsave2" })
</td>
</tr>
<tr>
<td>
<label>
Journal Code:</label>
</td>
<td>
#Html.DropDownListFor(m => m.JournalCode, new System.Web.Mvc.SelectList(Model.JournalsWithCallForPaperHtmlList, "JournalCode", "JournalCode"), new { id= "btnchange2" })
</td>
</tr>
and call the id
$('#btnsave1').click(function (event) {
//do stuff here
}
If you want to do an operation on more than one DDL dont use onclick.. Use :
#Html.DropDownListFor(m => m.OwnerId, new System.Web.Mvc.SelectList(Model.CallForPaperJournalOwnersList, "OwnerId", "Owner"), new { #class = "myclass" })
and in jquery just go :
$('.myclass').click(function (event) {
//do stuff here
}
In my project i am doing like this
I fill my state dropdownl with country id like this
this is my Dropdownlist
#Html.DropDownListFor(model => model.CountryId, new SelectList(Model.Countries, "ID", "Name"), "select", new { #ID = "ddlCountry", #class = "text", Style = "width: 150px;", onchange = "javascript:cascadingdropdown();" })
i create a javascript function like this it's below
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (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.');
}
});
}
i think this will help you...

Categories

Resources