MVC Partial view using ajax - c#

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)

Related

How to get an Id from one table and save it to another table in ASP.NET Core, repository pattern

This is Schedule Exam service:
public int AddSchedule(ScheduleExamViewModel schedule)
{
var newSchedule = new ScheduleExam()
{
ExamDate = schedule.ExamDate,
SubjectId = schedule.SubjectId,
StudentId = schedule.StudentId,
Status = schedule.Status
};
_context.ScheduleExams.Add(newSchedule);
_context.SaveChanges();
return newSchedule.Id;
}
This is Schedule exam controller :
// GET: ScheduleExamController/Create
public IActionResult Create()
{
var model = new ScheduleExamViewModel();
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name");
return View(model);
}
// POST: ScheduleExamController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ScheduleExamViewModel schedule)
{
if (ModelState.IsValid)
{
int id = _ischeduleExam.AddSchedule(schedule);
if (id > 0)
{
return RedirectToAction(nameof(Create));
}
}
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name");
return View(schedule);
}
I want to get the Id of student and save it to table of schedule exam by clicking on the "Schedule New Exam"
This is the index.cshtml of the Student table:
<table class="table table-hover table-bordered table-condensed">
<thead class="table-color text-white">
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>Schedule New Exam</th>
<th>Properties</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
<a asp-action="Create" asp-controller="ScheduleExam", asp-route-id="#item.Id">Schedule New Exam</a>
</td>
<td>
#Html.ActionLink(" ", "Edit", new { id = item.Id }, new { #class = "fa fa-edit", title = "Edit" }) |
#Html.ActionLink(" ", "Details", new { id = item.Id }, new { #class = "fa fa-info-circle", title = "More details" }) |
#Html.ActionLink(" ", "Delete", new { id = item.Id }, new { #class = "fa fa-trash", title = "Delete" })
</td>
</tr>
}
</tbody>
</table>
and this is the create.csthml page of schedule exam:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ExamDate" class="control-label"></label>
<input asp-for="ExamDate" class="form-control" />
<span asp-validation-for="ExamDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StudentId" class="control-label"></label>
<input asp-for="StudentId" class="form-control" value="#ViewBag.model.Id" />
<span asp-validation-for="StudentId" class="text-danger"></span>
</div>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><strong>Subject:</strong></span>
</div><br />
<select asp-for="SubjectId" class="form-control input-hover" asp-items="ViewBag.Subject">
<option value="">Please choose a subject...</option>
</select>
<span asp-validation-for="SubjectId " class="text-danger"></span>
</div><br />
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
but when I click on the Schedule New exam in index.cshtml of Student table I get this error:
RuntimeBinderException: Cannot perform runtime binding on a null reference
CallSite.Target(Closure , CallSite , object )
CallSite.Target(Closure , CallSite , object )
System.Dynamic.UpdateDelegates.UpdateAndExecute1<T0, TRet>(CallSite site, T0 arg0)
AspNetCore.Views_ScheduleExam_Create.b__22_0() in Create.cshtml
+
<input asp-for="StudentId" class="form-control" value="#ViewBag.model.Id" />
Please solve it by details and I'm using ASP.NET Core 3.1 MVC using a repository pattern.
Thank you
first of all, you should get an Id inside Create-Action and set for students :
public IActionResult Create(int Id)
{
var model = new ScheduleExamViewModel();
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name" , Id);
return View(model);
}
Second, I can't find a drop-down list for Students in your view. I think you should set Id in the controller for ViewModel.
var model = new ScheduleExamViewModel();
mode.Id = Id;
Third, you passed a model to the View and you can get information from the Model.
#model ScheduleExamViewModel
<input asp-for="StudentId" class="form-control" value="#Model.Id" />

modal problem partial view same data show but different item selected

Hi Everyone, I try to used the modal to avoid having multiple pages. but I got a problem, first, I click the view button and it will display to modal the right information; but when I click other view button instead the next data, it display the previous data.
second, after I select the view button and try to select the new shoes button (expectation must be display the new module in modal) it display the data of the previous item I select in view button:
Controller:
public ActionResult Index() //main page
{
var result = _Context.Shoeses.Include(x => x.Supply).ToList();
return View(result);
}
public ActionResult New() //create new product
{
var SupplierCategory = _Context.Suppliers.ToList();
var listOfSupplier = new ShoesViewModel
{
Supply = SupplierCategory
};
return PartialView(listOfSupplier);
}
public ActionResult Details(int id) //view selected data
{
Shoes productItem = new Shoes();
productItem = _Context.Shoeses.Find(id);
return PartialView("_Details", productItem);
}
View: Index
#model IEnumerable<ShoeInformation.Models.Shoes>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<h2>Tindahan sa Bahay ni Tatang Benjamin</h2>
<br />
<br />
//my modal
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title">Details</h3>
</div>
<div class="modal-body" id="modalBody">
Testing Only
</div>
</div>
</div>
</div>
//my modal
<p>#Html.ActionLink("New Shoes", "New", "Shoes", new { id="btn_Modal"}, new { #class = "btn btn-primary btn-lg",#data_toggle="modal" ,#data_target="#myModal"})</p>
<table class="table table-striped table-hover ">
<tr>
<th>Product ID
</th>
<th>Product Code
</th>
<th>Product Name
</th>
<th>Item Size
</th>
<th>Supplier
</th>
<th>Available Quantity
</th>
<th>Unit Price (Php)
</th>
<th>Action
</th>
</tr>
#foreach (var shoes in Model)
{
<tr class="success">
<td>
#shoes.Id
</td>
<td>
#shoes.ProductCode
</td>
<td>
#Html.ActionLink(#shoes.ProductName, "Edit", "Shoes", new { id=shoes.Id})
</td>
<td>
#shoes.ItemSize
</td>
<td>
<input type="hidden" value="#shoes.Id" id="hiddenval" />
#Html.HiddenFor(x => shoes.Id)
#Html.DisplayFor(x => shoes.Supply.SupplierName)
</td>
<td>
#shoes.ItemQty
</td>
<td>
#shoes.ItemUnitPrice
</td>
<td>
#Html.ActionLink("View", "Details", "Shoes", new { id=shoes.Id}, new { #class = "view-Modal",#data_toggle="modal" ,#data_target="#myModal"})
</td>
</tr>
}
</table>
#*Open Modal Testing*#
#section scripts
{
<script src="~/Scripts/jquery.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#myModal').hide();
$("#btn_Modal").click(function () {
$('#myModal').modal('show');
});
$(".view-Modal").click(function () {
var productId =
$(this).closest('tr').find('#hiddenval').val();
$.ajax({
type: 'POST',
url: '/Shoes/Details',
data: { id: productId },
success: function (response)
{
$('#modalBody').html(response);
$('#myModal').modal('show');
}
});
})
$(".close").click(function ()
{
console.log("Clear All");
});
});
</script>
}
partial view: _details
#model ShoeInformation.Models.Shoes
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
<table class="tablemodel">
<tr>
<tr>
#Html.DisplayFor(x=>x.Id)
</tr>
<tr>
#Html.DisplayFor(x=>x.ProductName)
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I try to breakpoint to see the problem but everything is working properly, however in the modal it display the same value
can someone please help me regarding to this matter
thanks in advance

Filling HTML Table with Dropwdownlists Change event in MVC

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 },

Model is null in controller action after ajaxPost in partial page

I am new to ASP mvc
I have a partial page like
#model IEnumerable<Sample.Models.Privilege>
#{
ViewBag.Title = "Details";
}
<script type="text/javascript">
function UpdatePrivilegeSuccess() {
}
function UpdatePrivilegeFailure() {
}
</script>
<div class="settingsTable" style="position: relative; width: 100%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<h2>Privilege</h2>
</div>
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.PrivilegeName)
</th>
<th>
#Html.DisplayNameFor(model => model.module.ModuleName)
</th>
<th>
#Html.Label("Option")
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PrivilegeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.module.ModuleName)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.Checked)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PrivilegeId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PrivilegeId })
</td>
</tr>
}
</table>
#using (Ajax.BeginForm("UpdatePrivilege", "RolePrivilegemapping",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "PrivilegeWrapper",
OnSuccess = "UpdatePrivilegeSuccess",
OnFailure = "UpdatePrivilegeFailure"
}))
{
<p>
<input type="submit" value="Update" />
</p>
#Html.ActionLink("Update", "UpdatePrivilege", "RolePrivilegemapping")
}
</div>
I am listing privileges in a table. But after the user click Update for updating model , Model is received as NULL in controller action
public ActionResult UpdatePrivilege(IEnumerable<sample.Models.Privilege> updatedPrivilege
{
return PartialView("_Privilege", One_Track.Models.DataProvider.OneTrackDataProvider.GetPtrackPrivilegeNames());
}
Why is this happening? Any help will be appreciated
You need to at least move the data that your posting into your form or nothing will be posted.
You will also need to index your collections so that the modelbinder will work.
This is done by using a for loop rather than a foreach.
If you need non-editable fields to re-bind you will have to provide them as hidden inputs. You can use HiddenFor for this. See them under the DisplayFor's below.
#using (Ajax.BeginForm("UpdatePrivilege", "RolePrivilegemapping",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "PrivilegeWrapper",
OnSuccess = "UpdatePrivilegeSuccess",
OnFailure = "UpdatePrivilegeFailure"
}))
{
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.PrivilegeName)
</th>
<th>
#Html.DisplayNameFor(model => model.module.ModuleName)
</th>
<th>
#Html.Label("Option")
</th>
<th>Action</th>
</tr>
#for(var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => modelItem[0].PrivilegeName)
#Html.HiddenFor(modelItem => modelItem[0].PrivilegeName)
</td>
<td>
#Html.DisplayFor(modelItem => Model[0].ModuleName)
#Html.HiddenFor(modelItem => modelItem[0].ModuleName)
</td>
<td>
#Html.CheckBoxFor(modelItem => Model[0].Checked)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PrivilegeId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PrivilegeId })
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Update" />
</p>
}

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.

Categories

Resources