Change modal form depending on the button clicked - asp.net-mvc

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!

Related

Calling a view from different models in 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

passing data to modal dialog from controller to partial view with viewmodel MVC Ajax

I want to pass data to modal dialog from my controller to partial view using view model but it isn't working.
When I tried passing data to my view model without modal dialog and it's fine for the result
I have put debug points and showing the value in my view model return to my partial view but it isn't displaying anything.
Code in my View
<div class="col-sm-btn">
<button type="button" id="btnSearchType" class="btn bg">
<i class="material-icons">search</i>
</button>
</div>
#Html.Partial("~/Views/Dialog/Type.cshtml");
<script>
$("#btnSearchType").click(function () {
$.ajax({
type: "GET",
url: '#Url.Action("ListType", "MasterMaterial")',
data: {
category: $("#txtCategory").val()
},
dataType: "html",
success: function (response) {
$('#type').modal('show');
},
error: function (response) {
alert("error");
}
});
});
Code in my Partial View
#model List<MVC_Client.Models.MasterType>
<div class="modal fade" id="type" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="defaultModalLabel">Type</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table id="listType" class="js-basic-example dataTable">
<thead>
<tr>
<th>Type Code</th>
<th>Type Namce</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var type in Model)
{
<tr>
<td>#type.TypeCode</td>
<td>#type.TypeName</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Code in my Controller
[HttpGet]
public ActionResult ListType(string category)
{
MasterTypeClient mtc = new MasterTypeClient();
List<MasterType> listType = new List<MasterType>();
listType = mtc.GetListTypes(category).ToList();
return PartialView("~/views/DialogPages/Type.cshtml", listType);
}
Code in my Model Client
public IEnumerable<MasterType> GetListTypes(string category)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("MasterType/Category/" + (category)).Result;
if (response.IsSuccessStatusCode)
return response.Content.ReadAsAsync<IEnumerable<MasterType>>().Result;
return null;
}
Code in my Model
public class MasterType
{
public string TypeCode { get; set; }
public string TypeName { get; set; }
}
And here is for the result
Result for my modal dialog
You're loading your PartialView when the View loads. It looks like you want to only show the modal PartialView after search is clicked.
I would go ahead and put the modal structure in the View and change the PartialView to just generate the table. Something like:
View
<div class="col-sm-btn">
<button type="button" id="btnSearchType" class="btn bg">
<i class="material-icons">search</i>
</button>
</div>
<div class="modal fade" id="type" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="defaultModalLabel">Type</h4>
</div>
<div class="modal-body table-placeholder">
</div>
</div>
</div>
</div>
<script>
$("#btnSearchType").click(function () {
$.ajax({
type: "GET",
url: '#Url.Action("ListType", "MasterMaterial")',
data: {
category: $("#txtCategory").val()
},
dataType: "html",
success: function (response) {
$('.table-placeholder').html(response);
$('#type').modal('show');
},
error: function (response) {
alert("error");
}
});
});
Partial View
#model List<MVC_Client.Models.MasterType>
<div class="table-responsive">
<table id="listType" class="js-basic-example dataTable">
<thead>
<tr>
<th>Type Code</th>
<th>Type Namce</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var type in Model)
{
<tr>
<td>#type.TypeCode</td>
<td>#type.TypeName</td>
</tr>
}
}
</tbody>
</table>
</div>

Replacing parent view with partial view from another partial view

This My Parent View In this i am calling partialview(_CityList.cshtml).
#model MedicalOrbit.City
#{
ViewBag.Title = "CreateCity";
}
<h2>Add City</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="Maindiv" class="col-lg-7">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>City Details</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="row">
<div class="col-sm-6 b-r">
#*<hr />*#
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>City Name:</label>
#*#Html.LabelFor(model => model.CityName, htmlAttributes: new { #class = "control-label col-md-2" })*#
<br>
<div >
#Html.EditorFor(model => model.CityName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter City" } })
#Html.ValidationMessageFor(model => model.CityName, "", new { #class = "text-danger" })
</div>
</div>
<br>
<div>
<input type="submit" value="Create" class="btn btn-w-m btn-primary" />
<input type="submit" value="Cancel" class="btn btn-w-m btn-success" />
</div>
</div>
<div>
<div id="CityList" class="col-sm-6">
#*#Html.Partial("_CityList");*#
#Html.Action("CityList", "City")
</div>
</div>
</div>
</div>
</div>
</div>
}
<div id="Editdiv">
#Html.Action("EditCity", "City")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Partial View(_CityList.cshtml)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CityName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CityName)
</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = item.CityID })*#
#Ajax.ActionLink("Edit City", "EditCity", "City", new AjaxOptions()
{
UpdateTargetId = "Maindiv",
InsertionMode = InsertionMode.ReplaceWith
})|
#Html.ActionLink("Details", "Details", new { id = item.CityID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CityID }) |
#Html.ActionLink("Area", "Area", new { #class = "btn btn-warning btn-circle btn-lg fa fa-times", id = item.CityID })
</td>
</tr>
}
</table>
following is my Controller Code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedicalOrbit.Controllers
{
public class CityController : Controller
{
MediOrbitDatabaseEntities db = new MediOrbitDatabaseEntities();
// GET: City
public ActionResult Index()
{
return View();
}
public ActionResult CityList()
{
return PartialView("_CityList", db.Cities.Where(x => x.status == false).ToList());
}
public ActionResult CreateCity()
{
return View();
}
// POST: City/CreateCity
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCity(City city)
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
city.Users = "ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Cities.Add(city);
db.SaveChanges();
return RedirectToAction("CreateCity");
}
return View(city);
}
public ActionResult EditCity(int? id)
{
City city = db.Cities.Where(x => x.CityID == id).FirstOrDefault();
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /Admin/City/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCity(City city)
{
if (ModelState.IsValid)
{
city.Users = "Ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
RedirectToAction("CreateCity");
}
return PartialView("_EditCity",city);
}
}
}
Now what i want is in _CityList.cshtml partial view when user clicks the edit actionlink then main parent view should be replace with another partial view(_EditCity.cshmtl).how i can achieve this.i m not experience in mvc so plz help me.
I am showing you how to do partial views. Hopefully, you will have enough take away to utilize partial views within partial views, if you want.
There might be extra code to help you.
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid4</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$('#LOCATION_NUMBER').click(function () {
var store = $('#storeNbr').val();
this.href = this.href.split("?")[0];
this.href = this.href + '?LOCATION_NUMBER=' + encodeURIComponent(store);
});
})
</script>
</head>
<body>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">My Modal</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<label class="btnIEFix">You can also, Click in Grey Area Outside Modal To Close</label>
<button title="You can also, Click in Grey Area Outside Modal To Close" type="button" class="btn btn-secondary bootBtnMargin" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#Html.HiddenFor(r => r.storeNbr, new { id = "storeNbr" })
#*https://stackoverflow.com/questions/5838273/actionlink-routevalue-from-a-textbox*#
#Ajax.ActionLink(
"Trigger Ajax",
"ReleaseVersion",
null,
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new
{
id = "LOCATION_NUMBER"})
<div id="result"></div>
</body>
</html>
Controller:
public class HomeController : Controller
{
public PartialViewResult ReleaseVersion(string LOCATION_NUMBER = "")
{
return PartialView("_ReleaseVersion"); //, model
}
public ActionResult IndexValid4()
{
var storeViewModel = new StoreViewModel { storeNbr = 5 };
return View(storeViewModel);
}
_ReleaseVersion partial view in shared folder:
release version partial view

Boostrap Modal not working on ASP.NET MVC

I have readed a lot of blogs and articles about showing MVC partial views using Boostrap modals. It seems that I have exactly what I'm seen on the material consulted but still it doesn't show the modal. I just need to show the partial view with the Album details in a modal. The controller is working fine when I load the URL through the browser.
This is the Index HTML code where the modal is shown:
<tbody>
#foreach( var album in Model.Albums)
{
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
}
</tbody>
Partial View
<div class="modal fade" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="albumModalLabel">Album Details</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<div class="row">
<label>Album<input class="form-control" type="text" id="title" /></label>
</div>
<div class="row">
<label>Artist <input class="form-control" type="text" id="artist" /></label>
</div>
<div class="row">
<label>Genre <input class="form-control" type="text" id="genre" /></label>
</div>
<div class="row">
<label>Year <input class="form-control" type="text" id="year" /></label>
</div>
</div>
<div class="col-md-8">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Track</th>
<th>Song Title</th>
<th>Length</th>
</tr>
</thead>
<tbody class="tracks"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
HomeController
[HttpGet]
public ActionResult Album(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var albumInfo = _service.GetAlbumInfo((int) id);
if (albumInfo == null) return HttpNotFound();
return PartialView("_Album", albumInfo);
}
Script
$(document).ready(function() {
$('.list-element').click(function () {
debugger;
var $buttonClicked = $(this);
var url = $buttonClicked.attr('data-url');
$.get(url, function (data) {
$('#albumContainer').html(data);
$('#albumModal').modal('show');
});
});
});
In almost all of the SO questions counsulted, they wasn't using data-target but I am. What do I need to modify to achieve that the modal shows?
VIEW
#model ShowModal
<table>
<tbody>
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModal">
#Html.Partial("_albumPartial", Model)
</div>
CONTROLLER
[HttpGet]
public ActionResult Album(int? id)
{
ShowModal modal = new ShowModal();
var albumInfo = _service.GetAlbumInfo((int) id);
modal.Info1 = albumInfo.Info1;//and other fields
return PartialView("_albumPartial", modal);
}
SCRIPT
<script>
$(document).ready(function () {
$("#albumModal").on("show.bs.modal", function (e) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // or button.attr("data-url") or get here just the id and create the URL here
$.get(url, function (data) {
$('#albumModal').html(data);
$('#albumModal').modal('show');
});
});
});
</script>

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