asp.net mvc 4 httppostedfilebase not passing to controller when using ajax modal popup - asp.net-mvc

There are some similar topics in forums, but there isn't any good answer. First question is that is it possible to pass httppostedfilebase to controller, when using modal popup?
When I am using regular model and view, then everything is working well, but as soon I make this view as partialview, then everything except file is passing to controller. File is getting null value.
List View where modalpopup is excecuting:
<button style="cursor:pointer" type="submit" class="fluent-big-button" onclick="ShowModal('#Url.Action("Create", "Device")')" >
Modal Popup View:
#using (Html.BeginForm("Create", "Device", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
<fieldset>
<legend>#Resources.Insert_New_Device</legend>
<div class="grid" style="margin: 0px auto">
<div class="row" style="margin: 0px auto">
<div class="span10">
<div class="row" style="margin: 0px auto">
<div style="white-space:nowrap" class="span2 readable-text"><label>#Resources.Device_No:</label> </div>
<div class="span3">
<div class="input-control text" data-role="input-control">
#Html.TextBoxFor(m => Model.No, new { required = "required", autofocus = "autofocus", #tabindex="1"})
#Html.ValidationMessageFor(m => Model.No)
<button tabindex="-1" class="btn-clear" type="button"></button>
</div>
</div>
<div style="white-space:nowrap" class="span2 readable-text"><label>Tootja:</label> </div>
<div class="span3">
<div class="input-control text" data-role="input-control">
#Html.TextBoxFor(m => Model.Manufacturer_Name, new { autofocus = "autofocus", #tabindex="2"})
#Html.ValidationMessageFor(m => Model.Manufacturer_Name)
<button tabindex="-1" class="btn-clear" type="button"></button>
</div>
</div>
</div>
<div class="row" style="margin: 0px auto">
<div style="white-space:nowrap" class="span2 readable-text"><label>Pilt:</label> </div>
<div class="span3">
<div class="fallback">
<input type="file" name="DeviceImage" id="DeviceImage" />
</div>
</div>
</div>
</div>
<div class="row" style="margin: 0px auto">
<div class="span10">#Html.ValidationMessage("CustomError")</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div class="grid" style="margin: 0px auto">
<div class="row" style="margin: 0px auto">
<div class="span4"></div>
<div class="span3">
<button class="button large span3" data-dismiss="modal">Cancel</button>
</div>
<div class="span3">
<input class="large span3 success" type="submit" value="Ok" />
</div>
</div>
</div>
</div>
}
Controller:
public ActionResult Create()
{
ViewBag.exsistingDevices = GetExsistingDevices();
return PartialView("_Create");
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin, Super")]
public async Task<ActionResult> Create(Device device, HttpPostedFileBase DeviceImage)
{
try
{
if (ModelState.IsValid)
{
SPDBContext db = new SPDBContext();
device.Last_Action_Date = DateTime.Now;
// Insert image
if (DeviceImage != null)
{
if (DeviceImage.ContentLength > (2 * 1024 * 1024) && DeviceImage.ContentLength < 1)
{
ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
}
var contentType = DeviceImage.ContentType;
device.Image = new byte[DeviceImage.ContentLength];
DeviceImage.InputStream.Read(device.Image, 0, DeviceImage.ContentLength);
}
db.Devices.Add(device);
await db.SaveChangesAsync();
return Json(new { success = true });
}
}
catch (Exception e)
{
ModelState.AddModelError("CustomError", String.Format("{0}: {1}",Resources.Resources.Insert_Failed, e.Message));
}
return PartialView("_Create", device);
}
Model:
[NotMapped]
public HttpPostedFileBase DeviceImage { get; set; }
public byte[] Image { get; set; }

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

Is it possible to generate new instances of the same form by clicking a button?

I'm working on a use case in my animal shelter web application where customers are able to register one or more animals at the same time. Ideally I'd like a button on the bottom left that generates another instance of the same form when clicked, so that multiple animal registrations can be saved to the database at once.
NewAnimalRegistration.cshtml:
#model NewAnimalRegistrationViewModel
<html>
<head>
<title>Register an animal</title>
<link rel="stylesheet" href="~/css/style.css"/>
</head>
<body>
<div class="container py-5">
<div class=" row">
<div class="col-md-10" mx-auto>
<div asp-validation-summary="All"></div>
<h1>Animal registration</h1>
<p>
We are happy to hear that you are interested in placing your animal in our shelter. Please fill in the fields below and our system will
check if there is room for your animal.
</p>
<form asp-action="RegistrationForm" method="post">
<div class="form-group row mt-5">
<div class="col-sm-6">
<label asp-for="Name">Name</label>
<input asp-for="Name" class="form-control"/>
</div>
</div>
<div class="form-group row mt-5">
<div class="col-sm-4">
<label asp-for="Gender" class="mr-3">Gender</label>
<select class="form-group" asp-for="Gender" asp-items="#ViewBag.Genders"></select>
</div>
<div class="col-sm-4">
<label asp-for="Type" class="mr-3">Animal type</label>
<select class="form-group" asp-for="Type" asp-items="#ViewBag.AnimalTypes"></select>
</div>
<div class="col-sm-4">
<label>Neutered</label>
<div class="form-check">
<input asp-for="IsNeutered" class="form-check-input" type="radio" value="true">
<label class="form-check-label" asp-for="IsNeutered">
Yes
</label>
</div>
<div class="form-check">
<input asp-for="IsNeutered" class="form-check-input" type="radio" value="false">
<label class="form-check-label" asp-for="IsNeutered">
No
</label>
</div>
</div>
</div>
<div class="form-group mt-5">
<label asp-for="Reason">Why are you deciding to put this animal up for adoption?</label>
<textarea class="form-control" asp-for="Reason" rows="6"></textarea>
</div>
<div class="float-right">
<a asp-controller="Home" asp-action="Index" class="btn btn-primary px-4">Cancel</a>
<button class="btn btn-primary px-4">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Is there a way to do this in .NET Core MVC? If yes, will I simply receive a list of all animal registrations through which I can simply loop and add them all to the database?
I made a demo based on your description, you can refer to it:
Model:
public class NewAnimalRegistrationViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Type { get; set; }
public bool IsNeutered { get; set; }
public string Reason { get; set; }
}
Index.cshtml:
#model NewAnimalRegistrationViewModel
<html>
<head>
<title>Register an animal</title>
</head>
<body>
<div class="container py-5">
<div class=" row">
<div class="col-md-10" mx-auto>
<div asp-validation-summary="All"></div>
<h1>Animal registration</h1>
<p>
We are happy to hear that you are interested in placing your animal in our shelter. Please fill in the fields below and our system will
check if there is room for your animal.
</p>
<form asp-action="RegistrationForm" method="post">
<div class="float-right">
<a asp-controller="Home" asp-action="Index" class="btn btn-primary px-4">Cancel</a>
<button class="btn btn-primary px-4">Save</button>
</div>
</form>
<a id="add" href='#' class="text-danger">register another animal</a>
</div>
</div>
</div>
</body>
</html>
#section scripts{
<script>
var count = 0;
$(function () {
var actionUrl = "/Home/AddRegistrationForm?count=" + count;
$.get(actionUrl).done(function (data) {
$('body').find('.float-right').before(data);
});
})
$("#add").on("click", function (e) {
e.preventDefault();
count++;
var actionUrl = "/Home/AddRegistrationForm?count=" + count;
$.get(actionUrl).done(function (data) {
$('body').find('.float-right').before(data);
});
})
</script>
}
_RegisterPartial.cshtml:
#model NewAnimalRegistrationViewModel
#{
int i = ViewBag.Count;
}
<h3>Anaimal #i</h3>
<div class="form-group row mt-5">
<div class="col-sm-6">
<label asp-for="Name">Name</label>
<input asp-for="Name" name="[#i].Name" class="form-control" />
</div>
</div>
<div class="form-group row mt-5">
<div class="col-sm-4">
<label asp-for="Gender" class="mr-3">Gender</label>
<select class="form-group" asp-for="Gender" name="[#i].Gender" asp-items="#ViewBag.Genders"></select>
</div>
<div class="col-sm-4">
<label asp-for="Type" class="mr-3">Animal type</label>
<select class="form-group" asp-for="Type" name="[#i].Type" asp-items="#ViewBag.AnimalTypes"></select>
</div>
<div class="col-sm-4">
<label>Neutered</label>
<div class="form-check">
<input asp-for="IsNeutered" name="[#i].IsNeutered" class="form-check-input" type="radio" value="true">
<label class="form-check-label" asp-for="IsNeutered">
Yes
</label>
</div>
<div class="form-check">
<input asp-for="IsNeutered" name="[#i].IsNeutered" class="form-check-input" type="radio" value="false">
<label class="form-check-label" asp-for="IsNeutered">
No
</label>
</div>
</div>
</div>
<div class="form-group mt-5">
<label asp-for="Reason">Why are you deciding to put this animal up for adoption?</label>
<textarea class="form-control" asp-for="Reason" name="[#i].Reason" rows="6"></textarea>
</div>
Controller:
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult AddRegistrationForm(int count)
{
ViewBag.Count = count;
ViewBag.Genders = new List<SelectListItem>
{
new SelectListItem{ Text = "Female", Value="Female"},
new SelectListItem{ Text = "Male", Value="Male"}
};
ViewBag.AnimalTypes = new List<SelectListItem>
{
new SelectListItem{ Text = "Cat", Value="Cat"},
new SelectListItem{ Text = "Dog", Value="Dog"}
};
return PartialView("_RegisterPartial");
}
[HttpPost]
public IActionResult RegistrationForm(List<NewAnimalRegistrationViewModel> model)
{
return View();
}
Result:

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.

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);

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