Calling a view from different models in ASP.NET MVC - asp.net-mvc

In my ASP.NET MVC application in the view, I'm calling another view that is not related to the current model. There I need some help that how to call the different model views from another view.
#model Asp_PASMVC.Models.VehicleService
#using Asp_PASMVC.Infrastructure
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> CompanyList = (List<SelectListItem>)TempData.Peek("ComapnyList");
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
Asp_PASMVC.Models.AppRequest RequestDetails = (Asp_PASMVC.Models.AppRequest)TempData.Peek("RequestDetails");
}
#{
Html.RenderPartial("_MainRequestView", RequestDetails);
}
#using (Html.BeginForm("WorkshopUpdate", "VehicleService", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.Req_Id)
#Html.AntiForgeryToken()
if (Model != null && Model.VehicleServiceApproveDetails != null)
{
foreach (Asp_PASMVC.Models.VehicleServiceApproveDetails Emp in Model.VehicleServiceApproveDetails)
{
Html.RenderPartial("_WorkshopUpdate", Emp);
}
}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Approver Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div>
<fieldset id="pnlApproverList" style="display:none">
<legend><h5>To whom you want to send this request for approval ? </h5> </legend>
<br />
<ul id="RequApprover" style="list-style-type: none">
#if (Model != null && Model.ApprovalPartyList != null)
{
foreach (Asp_PASMVC.Models.ApprovalParty Emp in Model.ApprovalPartyList)
{
Html.RenderPartial("_ApprovalView", Emp);
}
}
</ul>
<button type="button" id="addAnotherApprover" class="btn btn-success" href="#" onclick="this.style.display = 'none';">Add</button>
<script type="text/javascript">
$(function () {
// $("#movieEditor").sortable();
$("#addAnotherApprover").click(function () {
$.get('/VehicleService/AddApproverToReq', function (template) {
$("#RequApprover").append(template);
});
});
});
</script>
<br />
</fieldset>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update and Sent" class="btn btn-success" />
</div>
</div>
</div>
}
<p>
#Html.ActionLink("Back to List", "Index")
</p>
So likewise here the model is VehicleService. So within that view, I want to call another view that is not within the vehicleservice model.
But I cannot load that partial view within this view. Is there any way to do this?
#model Asp_PASMVC.Models.ApprovalParty
#using Asp_PASMVC.Infrastructure
#{
string UserLvel = TempData.Peek("UserLevelClaims").ToString();
}
<li style="padding-bottom:15px">
#using (Html.BeginCollectionItem("ApprovalPartyList"))
{
<div class="row">
<div class="col-md-5 col-sm-5">
<div class="form-group">
<label>
#Html.RadioButtonFor(m => m.Approve_Type, false)
<span class="radiomargin">For Manager</span>
</label>
<br />
#if (UserLvel != "1")
{
<label>
#Html.RadioButtonFor(m => m.Approve_Type, true)
<span class="radiomargin">For Top Manager </span>
</label>
#Html.ValidationMessageFor(model => model.Approve_Type, "", new { #class = "text-danger" })
}
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
Select the Approver
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { #id = "ddlEmployees", #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Approver_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
</li>

Create a ViewModel which can have both Properties and pass that viewmodel to View
Model class:
public class VehicleSerivceViewModel
{
public VehicleService VehicleService { get; set; }
public ApprovalParty ApprovalParty { get; set; }
}
In View :
#model Asp_PASMVC.Models.VehicleServiceVewModel
pass ViewModel to partial as below:
#Model.ApprovalParty

Related

How to reference a view model property in Asp.Net MVC - Razor view

In my razor view, in the "Panel area - to hold the comment button", I am trying to referencing the view models property BlogPublishedByBlogId.BlogId but I get - "the name BlogPublishedByBlogId does not exist in the current context".
However, I am able to reference the other properties fine using Lamda: model => model.BlogPublishedByBlogId.CreatedDateTime
How do I reference the 'blogId' in the "Panel area - to hold the comment button" area?
#model GbngWebClient.Models.BlogPublishedByBlogIdVM
<h2 class="page-header"><span class="blogtitle">#Session["BlogTitle"]</span></h2>
#{
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#if (Model != null)
{
<div class="panel panel-default toppanel">
<div class="panel-body">
<div class="row">
<div class="col-md-2">
#Html.LabelFor(model => model.BlogPublishedByBlogId.CreatedDateTime)
#Html.TextBoxFor(model => model.BlogPublishedByBlogId.CreatedDateTime, new { #class = "form-control", #disabled = "disabled" })
</div>
<div class="col-md-2">
#Html.LabelFor(model => model.BlogPublishedByBlogId.ModifiedDateTime)
#Html.TextBoxFor(model => model.BlogPublishedByBlogId.ModifiedDateTime, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<br />
<div class="row">
<div>
#Html.TextAreaFor(model => model.BlogPublishedByBlogId.BlogContent, new { #class = "form-control blogContent", #disabled = "disabled" })
</div>
</div>
</div>
#* Panel area - to hold the comment button. *#
<div class="panel-footer">
<button type="button" class="btn btn-default Comment" data-id="BlogPublishedByBlogId.BlogId" value="Comment">
<span class="glyphicon glyphicon-comment" aria-hidden="true"></span> Get Comment(s)
</button>
</div>
<div id="#string.Format("{0}_{1}","commentsBlock", BlogPublishedByBlogId.BlogId)" style="border: 1px solid #f1eaea; background-color: #eaf2ff;">
<div class="AddCommentArea" style="margin-left: 30%; margin-bottom: 5px; margin-top: 8px;">
<input type="text" id="#string.Format("{0}_{1}", "comment", BlogPublishedByBlogId.BlogId)" class="form-control" placeholder="Add a Comment about the blog..." style="display: inline;" />
<button type="button" class="btn btn-default addComment" data-id="BlogPublishedByBlogId.BlogId"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
</div>
</div>
</div>
}
The view model:
namespace GbngWebClient.Models
{
public class BlogPublishedByBlogIdVM
{
public BlogPublishedByBlogIdVM()
{
this.BlogPublishedByBlogId = new BlogPublishedByBlogId();
}
public BlogPublishedByBlogId BlogPublishedByBlogId { get; set; }
}
}
I added #Model to the front of:
BlogPublishedByBlogId.BlogId.

Html.CheckBoxFor Returning Incorrect Value If Originally Unchecked

I have a ViewModel containing information for an object called ContactEvent. ContactEvent has a boolean called IsActive. I'm using #Html.CheckBoxFor() for a checkbox to let the user alter its value. The problem is that if the value is originally true and the user sets it to false, the model passed through the POST has the updated value. But if the value is originally false, the model passed through the POST always returns false still. I have no idea what is causing it.
View
#model ContactEventViewModel
#{
ViewBag.Title = "Contact Event";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script src="~/datatables/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="~/datatables/css/jquery.dataTables.min.css" />
</head>
<body>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
#using (Html.BeginForm("ContactEvent", "ContactEvents", FormMethod.Post))
{
<h1>Edit Contact Event</h1>
#Html.HiddenFor(Model => Model.ContactEvent.ContactEventSysID, new { #Value = Model.ContactEvent.ContactEventSysID })
<div class="form-group row">
<label>Customer</label>
<div class="col-md-7 col-lg-7">
<Label>#String.Format("{1}, {0}", Model.Customer.FirstName, Model.Customer.LastName)</Label>
#Html.HiddenFor(Model => Model.Customer.CustomerSysID, new { #Value = Model.Customer.CustomerSysID })
</div>
</div>
<div class="form-group row">
<label>Date</label>
<div class="col-md-7 col-lg-7">
#Html.EditorFor(model => model.ContactEvent.Date, new { htmlAttributes = new { #class = "datepicker", #Name = "date", #PlaceHolder = "mm/dd/yyyy" } })
</div>
</div>
<div class="form-group row">
<label>Event Type</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.ContactEventTypeSysID, new SelectList(Model.ListOfContactEventTypes, "ContactEventTypeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Outcome</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.OutcomeSysID, new SelectList(Model.ListOfOutcomes, "OutcomeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Note</label>
<div class="col-md-7 col-lg-7">
#Html.TextBoxFor(Model => Model.ContactEvent.Note, new { #Value = Model.ContactEvent.Note })
</div>
</div>
<div class="form-group row">
<label>Created Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.CreatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Last Updated Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.LastUpdatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Active?</label>
<div class="col-md-7 col-lg-7">
#Html.CheckBoxFor(Model => Model.ContactEvent.IsActive, new { #Value = Model.ContactEvent.IsActive })
</div>
</div>
<input type="submit" id="updateButton" value="Submit" />
}
</div>
</body>
Method in Controller
[HttpPost]
public IActionResult ContactEvent(ContactEventViewModel contactEventViewModel)
{
if (ModelState.IsValid)
{
string connectionString = Startup.ConnectionString;
string query = "UPDATE [CRM].[dbo].[ContactEvent] " +
"SET [Date]=#Date, [ContactEventTypeSysID]=#ContactEventTypeSysID, [OutcomeSysID]=#OutcomeSysID, [Note]=#Note, [LastUpdatedDate]=#LastUpdatedDate, [IsActive]=#IsActive " +
"WHERE [ContactEventSysID]=#ContactEventSysID";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Date", contactEventViewModel.ContactEvent.Date);
command.Parameters.AddWithValue("#ContactEventTypeSysID", contactEventViewModel.ContactEvent.ContactEventTypeSysID);
command.Parameters.AddWithValue("#OutcomeSysID", contactEventViewModel.ContactEvent.OutcomeSysID);
if (contactEventViewModel.ContactEvent.Note == null)
{
command.Parameters.AddWithValue("#Note", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("#Note", contactEventViewModel.ContactEvent.Note);
}
command.Parameters.AddWithValue("#LastUpdatedDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
command.Parameters.AddWithValue("#IsActive", contactEventViewModel.ContactEvent.IsActive);
command.Parameters.AddWithValue("#ContactEventSysID", contactEventViewModel.ContactEvent.ContactEventSysID);
connection.Open();
command.ExecuteNonQuery();
}
}
}
return RedirectToAction("ContactEvent", "ContactEvents", new { ContactEventSysID = contactEventViewModel.ContactEvent.ContactEventSysID });
}
Let me know if you need any other code. Thanks in advance.
Please remove #Value = Model.ContactEvent.IsActive. This will let your model properly handle the value. Do not set any values unless you are sure, that you want to override model behavior.

The Model Passed to Dictionary is of one type whereas the Dictionary Requires Model Item of Type ViewModels

I am working with the partial views to attain a functionality in which I have to delete data from two tables having a one to many relationship in database. For this, I am using same “Delete” function in controller for both tables. I have added two models for these tables in the Delete view using ViewModels and have rendered both partial views in the main Delete Page to display relevant data on each delete view but after doing all this coding I am getting the following error.
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.tblPatientBill_804486DE0CB5E4B1C416CFC35E7B001C20B1FDB3674F40F1811012FFC9BAA908', but this dictionary requires a model item of type 'HMS.ViewModels.DeleteViewModel'.
Here is my Code Details:
PatientsBillController:
public ActionResult Delete(int? id,DeleteViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PatientsBillViewModel billmodell = new PatientsBillViewModel();
PatientsBillDetailViewModel billdetailmodell = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (billdetail == null)
{
if (bill == null)
{
return HttpNotFound();
}
else
{
billmodell.ID = bill.ID;
billmodell.PatientAppointmentID = bill.PatientAppointmentID;
billmodell.BillNo = bill.BillNo;
billmodell.Amount = bill.Amount;
billmodell.Discount = bill.Discount;
billmodell.CreatedAt = bill.CreatedAt;
billmodell.CreatedBy = bill.CreatedBy;
billmodell.Description = bill.Description;
return View(billmodell);
}
}
else
{
billdetailmodell.ID = billdetail.ID;
billdetailmodell.PatientBillID = billdetail.PatientBillID;
billdetailmodell.Amount = billdetail.Amount;
billdetailmodell.CreatedAt = billdetail.CreatedAt;
billdetailmodell.CreatedBy = billdetail.CreatedBy;
billdetailmodell.Description = billdetail.Description;
return View(billdetail);
}
}
Delete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "Delete";
Layout = null;
}
#{Html.RenderPartial("PatientsBillDelete", Model); }
#{Html.RenderPartial("PatientsBillDetail", Model); }
ViewModel.cs:
public class DeleteViewModel
{
public PatientsBillViewModel billmodel { set; get; }
public PatientsBillDetailViewModel billdetailmodel { set; get; }
}
public class PatientsBillViewModel
{
public int ID { get; set; }
public int PatientAppointmentID { get; set; }
public string BillNo { get; set; }
public float Amount { get; set; }
public float Discount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
public class PatientsBillDetailViewModel
{
public int ID { get; set; }
public int PatientBillID { get; set; }
public float Amount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
PartialViews are:
PatientBillDelete.cshtml
PatientBillDetail.cshtml
PatientBillDelete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.ID)
<br />
#Html.DisplayFor(m => m.billmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.PatientAppointmentID)
<br />
#Html.DisplayFor(m => m.billmodel.PatientAppointmentID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.BillNo)
<br />
#Html.DisplayFor(m => m.billmodel.BillNo)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Amount)
<br />
#Html.DisplayFor(m => m.billmodel.Amount)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Discount)
<br />
#Html.DisplayFor(m => m.billmodel.Discount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedAt)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedBy)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Description)
<br />
#Html.DisplayFor(m => m.billmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(m => m.billmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
PatientsBillDetail.cshtml
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.ID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.PatientBillID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.PatientBillID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Amount)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Amount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedAt)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedBy)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Description)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(model => model.billdetailmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
I think there is problem with my controller logic how can I look for different ids passed in the Delete function and check in two different table and pass result to viewmodel?
Please tell me what I am doing wrong in it. Thanks in advance
You are actually returning returning wrong object to your View. You should be passing the DeleteViewModel object back to your View something like :
DeleteViewModel deleteViewModel = new DeleteViewModel ();
deleteViewModel.billmodell = billmodell;
deleteViewModel.billdetailmodel = billdetailmodell;
and then pass it in your View() method call:
return View(deleteViewModel);
Your code after loading records from db should be like:
DeleteViewModel deleteViewModel = new DeleteViewModel();
deleteViewModel.billmodell = new PatientsBillViewModel(); ;
deleteViewModel.billdetailmodel = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (bill != null)
{
deleteViewModel.billmodell.ID = bill.ID;
deleteViewModel.billmodell.PatientAppointmentID = bill.PatientAppointmentID;
deleteViewModel.billmodell.BillNo = bill.BillNo;
deleteViewModel.billmodell.Amount = bill.Amount;
deleteViewModel.billmodell.Discount = bill.Discount;
deleteViewModel.billmodell.CreatedAt = bill.CreatedAt;
deleteViewModel.billmodell.CreatedBy = bill.CreatedBy;
deleteViewModel.billmodell.Description = bill.Description;
}
if(billdetail != null)
{
deleteViewModel.billdetailmodel.ID = billdetail.ID;
deleteViewModel.billdetailmodel.PatientBillID = billdetail.PatientBillID;
deleteViewModel.billdetailmodel.Amount = billdetail.Amount;
deleteViewModel.billdetailmodel.CreatedAt = billdetail.CreatedAt;
deleteViewModel.billdetailmodel.CreatedBy = billdetail.CreatedBy;
deleteViewModel.billdetailmodel.Description = billdetail.Description;
}
return View(deleteViewModel);

Change modal form depending on the button clicked

I have a table showing the information of the users, with an edit button for each one.
I want to show a modal form with the details for the user I want to edit, but I don't know how to get the details from the list, and passing them to the modal as a model.
Here is my View:
#model MyApp.Models.User
#{
ViewBag.Title = "Users";
var roles = new List<string> { "Manager", "Admin" };
var userRoles = (List<string>)ViewData["userRoles"];
}
<h2>#ViewBag.Title</h2>
#if (userRoles.Any(u => roles.Contains(u)))
{
using (Html.BeginForm("Update", "Admin", FormMethod.Post, new { id = "update-form", value = "" }))
{
<div class="modal fade" id="user-editor" >
<div class="modal-header">
<a class="close" data-dismiss="modal"><h3>×</h3></a>
<h3 id="modal-title">Edit User</h3>
</div>
<div class="modal-body">
<div class="form-group">
#Html.Label("Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Age", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Age, new { #class = "form-control" })
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
<input type="submit" class="btn btn-primary" value="Save Changes" />
</div>
</div>
}
}
<table class="table-bordered table-hover" id="tbusers">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
#if (userRoles.Any(u => roles.Contains(u)))
{
<th>Edit</th>
}
</tr>
</thead>
<tbody>
#foreach (var u in users)
{
<tr id="#u.Id">
<td>#u.Name</td>
<td>#u.Age</td>
#if (userRoles.Any(u => roles.Contains(u)))
{
<td><a type="button" class="btn edit-btn" href="#user-editor" data-toggle="modal">Edit</a></td>
}
</tr>
}
</tbody>
</table>
I've created a testing sample which will help you understand how can you achieve this.
Index.cshtml which will show a list of employees
#model IEnumerable<MvcApplication1.Models.Employee>
#using MvcApplication1.Models;
<h2>Index</h2>
<table>
#foreach (Employee item in Model)
{
<tr>
<td>#Html.ActionLink(#item.EmployeeName, "Name", new { id = item.ID })</td>
<td>
<button type="button" data-id='#item.ID' class="anchorDetail btn btn-info btn-sm" data-toggle="modal"
data-target="#myModal">
Open Large Modal</button></td>
</tr>
}
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
At the same page, reference the following scripts
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
JQuery AJAX call for getting/setting the data of individual employee from ActionMethod at the same page
<script>
$(document).ready(function () {
var TeamDetailPostBackURL = '/Employee/Details';
$(document).on('click', '.anchorDetail', function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('.modal-body').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
$("#closbtn").click(function () {
$('#myModal').modal('hide');
});
});
Now Create a class of Employee(because i'm not using EF)
public class Employee
{
public int ID { get; set; }
public string EmployeeName { get; set; }
}
Create controller named Employee and 2 ActionMethods like these:
public ActionResult Index()
{
return View(emp);//sends a List of employees to Index View
}
public ActionResult Details(int Id)
{
return PartialView("Details",
emp.Where(x=>x.ID==Convert.ToInt32(Id)).FirstOrDefault());
}
I'm returning PartialView because I need to load a page within a page.
Details.cshtml
#model MvcApplication1.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.ID)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.ID)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.EmployeeName)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.EmployeeName)
</div>
</fieldset>
<p>#Html.ActionLink("Back to List", "Index")</p>
When you execute and visit the Index page of Employee, you'll see screen like this:
And the Modal Dialog with results will be shown like this:
Note: You need to add reference of jquery and Bootstrap and you can further design/customize it according to your needs
Hope it helps!

ASP.Net MVC Show/Hide Content

Ok I have the following View
#model IEnumerable<WebApplication3.Models.user>
#{
ViewBag.Title = "Password Management";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section title {<h1>#ViewBag.Title</h1>}
<div id="page-block" class="page-block-three row">
<div style="margin-top: 30px;" class="col-lg-offset-2 col-lg-8">
#using (Html.BeginForm())
{
<div class="input-group">
#Html.TextBox("SearchString", null, new { #class = "form-control ccl-form", #style = "z-index: 10", #placeholder = "Enter Username"})
<div class="input-group-btn">
<button class="btn ccl-btn ccl-btn-red ccl-btn-search" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
}
</div>
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
</div>
What I want to be able to do is hide the following div
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
Then show that Div when the submit button is clicked
My Controller looks like the following
public class PasswordController : Controller
{
private CCLPasswordManagementDBEntities db = new CCLPasswordManagementDBEntities();
public ActionResult Search(string searchString)
{
var users = from x in db.users select x;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(x => x.UserName.ToUpper().Contains(searchString.ToUpper()));
}
return View(users);
}
}
At the moment the div is constantly shown and updates when the submit button is pressed but I want to hide that div until someone presses the submit button then it can show.
Thanks in advance for the help.
Change your code in the controller to this:
public ActionResult Search(string searchString)
{
var users = from x in db.users select x;
ViewBag.ShowList = false;
if (!String.IsNullOrEmpty(searchString))
{
ViewBag.ShowList = true;
users = users.Where(x => x.UserName.ToUpper().Contains(searchString.ToUpper()));
}
return View(users);
}
And change your view to this:
#model IEnumerable<WebApplication3.Models.user>
#{
ViewBag.Title = "Password Management";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section title {<h1>#ViewBag.Title</h1>}
<div id="page-block" class="page-block-three row">
<div style="margin-top: 30px;" class="col-lg-offset-2 col-lg-8">
#using (Html.BeginForm())
{
<div class="input-group">
#Html.TextBox("SearchString", null, new { #class = "form-control ccl-form", #style = "z-index: 10", #placeholder = "Enter Username"})
<div class="input-group-btn">
<button class="btn ccl-btn ccl-btn-red ccl-btn-search" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
}
</div>
#if(ViewBag.ShowList){
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
}
</div>
You can try having a flag (ViewBag.isShown = false;)
When the page refreshes, it will show your div.
Code should be like below:
if (ViewBag.isShown == true)
{
..your for each block..
}

Resources