Unable to display Modal popup in the same page MVC - c#

I have a requirement where I need to display a Modal popup. When the user clicks on the link inside a grid, then that has to open a modal popup with the respective values. But currently it is taking me to a new page instead of displaying it as a modal popup in the same page. Can someone have a look at this an tell me what is going wrong?
Popup is being called here:
grid.AddColumn("ProductName", "Product",
format: (item) =>
{
return Warehouse.Helpers.HtmlHelpers.DialogFormLink2(Html, item.ProductName, #Url.Content("~/Service/ProductCategory/ProductTransactionsPopupView?ProductID=" + #item.ProductID + "&ProgramID=" + Model.ProgramID + "&Status=" + item.ProductStatus + "&ProductRequestID=" + ViewBag.ProductRequestID), null, "Product History", "dialog", "", #Url.Action("ProductProfile"));
});
Controller:
public ActionResult ProductTransactionsPopupView(int ProductID, string ProductStatus, int? ProductRequestID = null)
{
var Program = GetProgram();
var mdl = new ProductTransactionsViewModel { ProgramID = Program.ProgramID, ProductID = ProductID };
try
{
var ProductTransactionResponse = _ServiceProduct.GetProductTransactions(Program.ProgramID, User.Name, ProductID);
mdl.ProductID = ProductTransactionResponse.ProductId;
mdl.Transactions = ProductTransactionResponse.ProductTransactions.ToList();
mdl.ProductName = ProductTransactionResponse.Product != null ? ProductTransactionResponse.Product.ProductName : "";
mdl.ProductStatus = ProductStatus;
}
catch (Exception ex)
{
mdl.ErrorMessage = "An error occured.";
}
ViewBag.ProductRequestID = ProductRequestID;
return View("ProductTransactions", mdl);
}
Model View:
#model Warehouse.Product.ProductTransactionsViewModel
#using Warehouse.Helpers;
#{
ViewBag.Title = "Product Transactions";
ViewBag.ProgramID = Model.ProgramID;
ViewBag.ProductName = Model.ProductName;
ViewBag.ProductID = Model.ProductID;
Layout = "~/Views/Shared/_PRPopupsLayout.cshtml";
var PRID = (int?)ViewBag.ProductRequestID;
}
<div class="DisplayMessage">
</div>
<div class="popupContentContainer">
#Html.Partial("_ProductTransactions")
</div>
<div style="text-align:center">
#if(Model.ProductStatus == "Active")
{
<input type="button" value="Generate Product Document" id="ProductInquiry" name="ProductInquiry" class="grey button" />
}
<input type="button" value="Exit" id="exit" name="exit" class="grey button" />
</div>

Related

How do i redirect to controller when a button is clicked inside of popup window in mvc5?

How do i redirect to controller when a button is clicked inside of popup window. I will explain my issue clearly .I have one form called VisitorsForm. In that i have one dropdown called Purpose of visit. If I select purpose of visit as "Trail "it open one pop-up window .After enter all the values which is inside of pop-up window and click the save button means it does not redirect to controller.
My VisitorsForm Screen
In the above image i have field called purpose of visit.if i select purpose of visit as Trial. It open the pop-up window. In pop-up window I entered all the values and click the save button means it didn't redirect to controller.
My Model(VisitorsViewModel)
public Nullable<System.Guid> POVisitID { get; set; }
public Nullable<System.Guid> CustomerTrialItemID { get; set; }
public System.Guid ItemID{ get; set; }
public int Quantity { get; set; }
My Controller
public ActionResult CreateCustomertrialForm(VisitorsViewModel visitorsformviewmodel)
{
var itemslist = Session["itemList"] as List<VisitorsViewModel>;
var customertrialformid = Guid.NewGuid();
var trialdateobj = DateTime.Now.Date;
var customertrialform = new CustomerTrialForm();
customertrialform.CustomerTrialFormID = customertrialformid;
customertrialform.TrialDate = trialdateobj;
customertrialform.Ends = visitorsformviewmodel.Ends;
customertrialform.CustomerTrialItemID = visitorsformviewmodel.CustomerTrialItemID;
var multipleitemlist = new List<CustomerTrialItem>();
foreach (var item in itemslist)
{
var customertrialitem = new CustomerTrialItem();
customertrialitem.CustomerTrialItemID = Guid.NewGuid();
customertrialitem.ItemID = item.ItemID;
customertrialitem.Quantity = item.Quantity;
db.CustomerTrialItems.Add(customertrialitem);
}
db.CustomerTrialForms.Add(customertrialform);
db.SaveChanges();
ModelState.Clear();
return View();
}
My View
#model CostToWafe.Areas.Sales.Models.VisitorsViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-sm-3">
<div class="form-group">
<span style="color: #f00">*</span>
<fieldset>
#Html.Label("Purpose of Visit", new { #class = "control-label", styles = "font-family: Arial;" })
#Html.DropDownList("POVisitID", null, "Select", new { #class = "form-control required" })
</div>
</div>
//pop-up window code inside of parent page
#using (Html.BeginForm("CreateCustomertrialForm", "VisitorsForm", new { Areas ="Sales"}))
{
<div id="Trial-dialog-modal" title="Trial Form" style="display:none">
<div class="box-body">
<div>Customer Name</div>
<div id="customername"></div>
#Html.HiddenFor(m => m.CustomerID, new { id = "customerid" })
#Html.LabelFor(model => model.SampleNo)
#Html.TextBoxFor(model => model.SampleNo, new { #class = "form-control", type = "text" })
#Html.LabelFor(model => model.SortName)
#Html.TextBoxFor(model => model.SortName, new { #class = "form-control", type = "text" })
//pop-up window Save button
<input type="button" value="Save" onclick="location.href='#Url.Action(" CreateCustomertrialForm", "VisitorsForm")'" />
}
//Second methid i used to save pop up window
//Pop up window Save button
<input id="Button1" class="btn btn-primary" type="button" value="Save" onclick="SaveCustomertrialform()" />
<script>
function SaveCustomertrialform() {
debugger;
var url = '#Url.Action("SaveCustomertrialForm", "VisitorsForm", new { Area = "Sales" })';
var CustomerID = $("#customerid").val();
var SampleNo = $("#SampleNo").val();
var SortName = $("#SortName").val();
var YarnCount = $("#YarnCount").val();
var CustomerTrialForm = {
"SampleNo": '' + SampleNo + '', "SortName": '' + SortName + '',
"YarnCount": '' + YarnCount + '', "Ends": '' + Ends + ''
};
$.ajaxSetup({ async: true });
$.post(url, CustomerTrialForm, function (data) {
alert("Success")
$("#dialog-modal").dialog("close");
});
}
</script>
//Parent Page Save Button
<button id="SaverBtn" type="submit" class="btn btn-success pull-left" value='EnterKey'>Save<i class="fa fa-save"></i></button>
</fieldSet>
}
I tried many ways to clear the issue.But I can't clear my issue. Any one help to resolve this issue.
Thanks.

How to fix System.NullReferenceException' occurred in App_Web_xxxx.dll in asp.net mvc?

This is a part of my view code for Index action of Manage Controller.
<div class="mngimg">
#using (Html.BeginForm("UploadPhoto", "Manage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="btn btn-default browseimg">
<input type="file" name="file" id="files" onchange="this.form.submit()" />
</div>
<div class="btn btn-default browseimg">
#Html.ActionLink("Remove Photo", "RemovePhoto", "Manage")
</div>
}
</div>
</div>
}
</dd>
<dt>Password:</dt>
<dd>
[
#if (Model.HasPassword) <!-- Here is my error. The Model is null -->
{
#Html.ActionLink("Change your password", "ChangePassword")
}
else
{
#Html.ActionLink("Create", "SetPassword")
}
]
</dd>
Whenever I open this page and click "Remove Photo" I keep getting an error saying that An exception of type 'System.NullReferenceException' occurred in App_Web_ckoryptg.dll but was not handled in user code. I tried debugging, but I am unable to figure out why my Model.HasPassword is becoming null. Here is my RemovePhoto Action from Manage Controller.
[HttpPost]
public async Task<ActionResult> UploadPhoto(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var user = await GetCurrentUserAsync();
var userId = user.Id;
var fileExt = Path.GetExtension(file.FileName);
var fnm = userId + ".png";
if (fileExt.ToLower().EndsWith(".png") || fileExt.ToLower().EndsWith(".jpg") || fileExt.ToLower().EndsWith(".gif"))// Important for security if saving in webroot
{
var filePath = HostingEnvironment.MapPath("~/Content/Images/") + fnm;
var directory = new DirectoryInfo(HostingEnvironment.MapPath("~/Content/Images/"));
if (directory.Exists == false)
{
directory.Create();
}
ViewBag.FilePath = filePath.ToString();
file.SaveAs(filePath);
return RedirectToAction("Index", new { Message = ManageMessageId.PhotoUploadSuccess });
}
else
{
return RedirectToAction("Index", new { Message = ManageMessageId.FileExtensionError });
}
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });// PRG
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(User.Identity.GetUserId());
}
I opened a default MVC project that comes with visual studio and I added these extra things that I followed from this tutorial ASP.NET upload images. How do I resolve this?
Edit:
This is my RemovePhoto action.
public ActionResult RemovePhoto()
{
string file = "~/Content/Images/" + User.Identity.GetUserId() + ".png";
if(System.IO.File.Exists(Server.MapPath(file)))
System.IO.File.Delete(Server.MapPath(file));
return View("Index");
}
Just Redirect back to your Index action. That way you don't have to instantiate your Index model in your RemovePhoto action. Can read more about this pattern here.

Asp.Net MVC : Insert data from form collection with List of values

As you can see in picture, I have a form where I continuously add items to the table below.
When I click "Save all" button, it posts all the table values to "InsertBulk" method.
And this is what I did in my view. I am created a form within the table. Set name and values for each input field. Made the input fields hidden, displayed only text and then on clicking save all button it posts all those value to the InsertBulk method.
#model FYPPharmAssistant.Models.InventoryModel.Manufacturer
#{
ViewBag.Title = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<label>Name</label><br />
#Html.EditorFor(m => m.ManufacturerName, new { htmlAttributes = new { #class = "form-control" } }) <br />
<label>Description</label><br />
#Html.EditorFor(m => m.Description, new { htmlAttributes = new { #class = "form-control" } })
<input type="submit" id="addmore" value="add" />
}
#using (Html.BeginForm("InsertBulk", "Manufacturer"))
{
<table id="table">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
</table>
<input type="submit" id="btnsaveall" value="Save all" />
}
<script>
$(document).on('ready', function () {
$('#addmore').on('click', function () {
var $table = $("#table");
$table.append("<tr> <td><input type='hidden' name='ManufacturerName' value='" + $('#ManufacturerName').val() + "' />" + $('#ManufacturerName').val() + "</td> <td><input type='hidden' name='Description' value='" + $('#Description').val() + "'>" + $('#Description').val() + "</td> <td><a href='javascript:void(0)' onclick='removeItem(this)'>Remove</a></td></tr>");
return false;
});
});
</script>
This is my InsertBulk method.
[HttpPost]
public void InsertBulk(FormCollection coll)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName"];
m.Description = coll["Description"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
Result :
Ans this is what I get in Result. How am I suppose to solve this ? Please help!
I also tried to count keys and loop through each in the InsertBulk method. But I think I did it all wrong.
int count = coll.Count;
if(count == 0)
{
return View("ChamForm", "Test");
}
else
{
for(int i = 0; i<count; i++)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName[" + i + "]"];
m.Description = coll["Description[" + i + "]"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
}*
If it is so why not split contents based on comma, save each of them in two different string array. Then loop through each array's item saving name and description on each loop.
public ActionResult Student(StudentModel model, FormCollection frm)
{
string XmlData = "<Parent>";
var stuclass = frm.GetValues("stuclass");
var InstituteId = frm.GetValues("Institute");
var obtmark = frm.GetValues("obtmark");
var totalmark = frm.GetValues("totalmark");
var per = frm.GetValues("per");
int count = stuclass.Count();
for (int i = 0; i < count; i++)
{
XmlData += "<child><stuclass>" + stuclass[i] + "</stuclass>"
+ "<InstituteId>" + InstituteId[i] + "</InstituteId>"
+ "<obtmark>" + obtmark[i] + "</obtmark>"
+ "<totalmark>" + totalmark[i] + "</totalmark>"
+ "<per>" + per[i] + "</per>"
+ "</child>";
}
XmlData += "</Parent>";
model.XmlData = XmlData;
var res = studal.Insertdtl(model);
return View();
}

Searching with a dropdown list in asp.net MVC

I'm new to ASP.NET MVC. I want to use selected items from my dropdownlist to search my database table. The dropdownlist was generated from a BOL model which automatically binds to the view.
Below are my code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using BOL;
namespace DentiCareApp.Areas.Admin.Controllers
{
[AllowAnonymous]
public class GenerateInvoiceController : Controller
{
private TreatmentBs objBs;
public GenerateInvoiceController()
{
objBs = new TreatmentBs();
}
// GET: Admin/GenerateInvoice
public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");
if (CompanyID == null)
{
return View();
}
else
{
return View(db.Treatments.Where(x => x.Company == CompanyID.Take(50)));
}
//return View();
}
Also below is the interface of view.
Secondly, I also want the search result to appear on the same page. How do I do this? If I create a separate action for this, I will need to create a separate view for it. Can partial view be used? If so how?
Below is the code to the View
#model BOL.GenerateInvoice
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p></p>
<p></p>
<p></p>
<h2>Quickly Generate Invoice</h2>
#using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
#Html.AntiForgeryToken()
<div class="">
<div>
#Html.DropDownList("MyCompany.CompanyId", (IEnumerable<SelectListItem>)ViewBag.CompanyId, "Select Company", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MyCompany.CompanyId, "", new { #class = "text-danger" })
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
}
Try this.
Controller action:
public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName", CompanyID); // preselect item in selectlist by CompanyID param
if (!String.IsNullOrWhiteSpace(CompanyID))
{
return View();
}
return View(db.Treatments.Where(x => x.CompanyID == CompanyID).Take(50));
}
View code:
#model IEnumerable<Treatment>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Quickly Generate Invoice</h2>
#using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.DropDownList("CompanyId", (SelectList)ViewBag.CompanyId, "Select Company", new { #class = "form-control" })
<input type="submit" value="Search" class="btn btn-primary" />
}
#if(Model != null && Model.Any())
{
foreach(var item in Model)
{
#Html.DisplayFor(model => item)
}
}
You can change the DisplayFor() here to show individual properties of the given Treatment, such as #Html.DisplayFor(model => model.TreatmentID) and such
The Above code worked for me but with little tweaks. Here are few modification I made to your code.
The parameter in the Index Action was changed from string to integer.
The Optional Parameter in the ViewBag.CompanyId was removed.
Lastly, the line if (!String.IsNullOrWhiteSpace(CompanyID)) and changed to if (CompanyID == 0) { return View(treatmentList);}
The result however is great as it worked like a charm! Thanks for your help!
// GET: Admin/ListTreatment
public ActionResult Index(string sortOrder, string sortBy, string Page, int CompanyID = 0)
{
ViewBag.sortOrder = sortOrder;
ViewBag.sortBy = sortBy;
var treatmentList = objBs.GetALL();
//ViewBag.employeeCompany = employeeCompany.Distinct();
switch (sortOrder)
{
case "Asc":
treatmentList = treatmentList.OrderBy(x => x.TreatmentDate).ToList();
break;
case "Desc":
treatmentList = treatmentList.OrderByDescending(x => x.TreatmentDate).ToList();
break;
default:
break;
}
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");
ViewBag.TotalPages = Math.Ceiling(objBs.GetALL().Where(x=>x.CompanyId > 0).Count()/10.0);
int page = int.Parse(Page == null ? "1" : Page);
ViewBag.Page = page;
treatmentList = treatmentList.Skip((page - 1) * 10).Take(10);
if (CompanyID == 0)
{
return View(treatmentList);
}
return View(db.Treatments.Where(x => x.CompanyId == CompanyID).Take(50));
}
First : for entity framework id should be nullable, so it can be accepted as argument, the action parameter should be int? CompanyID
Second : the comparison is not correct with (CompanyID == 0)
It should be (CompanyID == null)

Getting information from my controller into onclick confirm(alert)

i try to confirm a sale and i need sum information about the product..
my View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber, new { id = "sn" })
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" id="btnSubmit"
onclick="if (confirm('The owner dealer price is : **#Model.OwnerPrice** . Are you sure?')) { return true; } else { return false; }" />
</p>
</fieldset>
}
i tryed with the ' $.getJSON ' like this:
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function ()
{
var serial = $("#sn");
var price = "";
var url = "";
url = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.getJSON(url,function(data)
{
alert(data.Value);
});
});
});
and on the controller
public ActionResult GetOwnerPrice(int sn)
{
var owner = db.Dealers.Single(s => s.DealerID == db.Dealers.Single(o => o.UserName == User.Identity.Name).OwnerDealerID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == sn).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
but i dont know how to return it to the onclick confirm msg or into my ViewModel..
any help?
The way in which you have written it, the #Model.OwnerPrice value must be known during page generation, since the template engine only has values that exist in your model when it does the template-data merge.
If you do know this value during page load, then simply use the value in your model exactly as you have, and if the user ever gets to this dialog, they will see the proper value.
If the value of this confirmation dialog is not known during page load, then you have the right idea to retrieve it via an Ajax call. The trick is to update the DOM with the new information when the call finishes. You can do this in three steps. First, change your dialog box:
First:
if (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
Second:
Declare a new global variable:
var ownerDealerPrice;
Third:
Get the price:
$.ajax({ url: "/GetOwnerPrice", type: "GET", data: "serial=" + serial })
.success(function (price) {ownerDealerPrice = price; }
});
finnaly i take the two answare =)
my view:
#model oCc.IPToGo.ViewModel.CardSaleViewModel
#{
ViewBag.Title = "Card Sale";
var ownerDealerPrice = 0;
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber)
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" />
</p>
</fieldset>
}
<script type="text/javascript">
$(document).submit(function()
{
var serial = "";
serial = $("#CardModel_SerialNumber").val();
var uurl = "";
uurl = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.ajaxSetup({ cache: false });
$.ajax({ async: false , url: uurl, dataype : 'json', method : 'GET'})
.success(function (price) {ownerDealerPrice = price;
$.ajaxSetup({ cache: true });
});
return (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
});
the controller code
public ActionResult GetOwnerPrice(string ID)
{
var currentDealer = db.Dealers.Single(o => o.UserName == User.Identity.Name);
var owner = db.Dealers.Single(s => s.DealerID ==currentDealer.OwnerDealerID);
var card = db.Cards.Single(s => s.SerialNumber == ID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == card.ProductID).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
Did you try $.ajax with async = false?
It will return control right into your click handler. Something like:
var tmp = 0;
$.ajax({
async = false,
url = ...,
dataype = 'json',
method = 'POST'})
.complete(function(data) {
tmp = data
});
if(confirm("my message here: " + tmp)) {... }

Categories