Popup to Upload files MVC - c#

I need to upload some xml files .For this I need to open from my MVC application a popup to load a file .I wrote the code below.In the controller I see the loaded file .
Upload.cshtml:
#using (#Html.BeginForm("UploadFile", "UploadFileController", FormMethod.Post, new { #id = "uploadForm", #enctype = "multipart/form-data" }))
{
<div>
#Html.TextBoxFor(m => m.FileName, new { type = "file" })
<button type="submit" class="btn">Upload</button>
</div>
}
Controller :
[HttpPost]
public ActionResult UploadFile(UploadFileModel uploadFileModel)
{
....
}
Model:
public class UploadFileModel
{
public int Id { set; get; }
public HttpPostedFileBase FileName { get; set; }
}
Now ,the "Upload.cshtml" is a part and appear in the home page .
1.How can I transform it in a separate form ?This part appear when I press a button.
2.How can I show in the search dialog just xml files ?
Thanks .

As it was mentioned before , it's front-end problem and nothing to do with c# and controller. So please Modify Upload.cshtml :
<button type="button" class="btn btn-default" id="showPopup">show popup</button>
<form id="uploadForm" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#Html.TextBoxFor(m => m.FileName, new { type = "file" })
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">close form</button>
<button type="submit" class="btn btn-success" id="">Upload</button>
</div>
</div>
</div>
Now with jquery :
$('#showPopup).click(function(){
$('#uploadForm').modal();
});
another option is Bootbox.js.
hope it helps.

Related

File upload using ASP.NET and HTML form

I am trying to create the functionality that allows to upload the image and store it into the db.
I have this input field in my HTML form:
#using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post))
{
<div class="modal" id="NewTRModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-xl" style="width:1250px;">
<div class="modal-content">
<div class="box5">
<div>
<label for="file-upload" class="custom-file-upload">
Upload Image1
</label>
<input id="file-upload" type="file" name="image1"/>
</div>
<div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4"> Submit</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">Hide</button>
</div>
</div>
</div>
</div>
}
And I am trying to get the file in my controller through
IFormFile file = Request.Form.Files["image1"];
However, for some reasons after I am clicking submit button the Request.Form.Files is empty.
I will appreciate any advice.
Web browsers will upload files properly only when the HTML form
element defines an enctype value of multipart/form-data:
#using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input id="file-upload" type="file" name="image1"/>
...
}
Without the enctype attribute, the browser will transmit only the name of the file and not its content.
Then in the controller action method you can use the same name as defined in the <input> tag as a parameter:
[HttpPost]
public ActionResult AddTR(HttpPostedFileBase image1)
{
if (image1 != null && image1.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath(#"~/"), Path.GetFileName(image1.FileName));
image1.SaveAs(path);
}
...
}
In case you are using ASP.NET Core (what you didn't mention in the question) you can define the enctype attribute and than use:
[HttpPost]
public IActionResult AddTR()
{
IFormFile file = Request.Form.Files["image1"];
....
}

How to get a Popup Window with Partial View in MVC 5

There seems to be a couple ways to do it. I really wanted this video to work for me. https://www.youtube.com/watch?v=oHWEs8XWA2U
Searching the web, I found it hard to find this question being asked recently, so I am wondering if newer and improved (easier) ways have been implemented.
Here is my Home controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult PartialViewTest()
{
return PartialView();
}
[HttpPost]
public ActionResult PartialViewTest(Person person)
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Here is my view I want the pop up on
#{
ViewBag.Title = "Contact";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn-block" style="width:225px">Modal </button>
<div class="modal fade" id="myModal" role="dialog" data-url='#Url.Action("PartialViewTest","Home")'></div>
<script type="text/javascript">
$(document).ready(function () {
$('.btn-block').click(function () {
var url = $('#myModal').data('url');
$.get(url, function (data) {
$("#myModal").html(data);
$("#myModal").modal('show');
});
});
});
</script>
Here is my partial view
<div class="container">
<div class="row">
<div class="col-sm-4"></div>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModal-label">Bootstrap Dialog</h4>
<div>
<div class="modal-body">
<div class="form-group">
<input type="text" placeholder="enter name" class="form-control" id="text" name="text" />
</div>
<div class="form-group">
<input type="text" placeholder="enter name id" class="form-control" id="text" name="text" />
</div>
<div class="form-group">
<input type="text" placeholder="adress" class="form-control" id="text" name="text" />
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btnOK" onclick="">OK</button>
<button class="btn btn-default" data-dismiss="modal" id="btnCancel">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
When I click the button as seen in the image above. Nothing happens. Why doesn't the popup view appear?
If this is not the best way to go about it, could you provide a link to a tutorial for the most professional, proper, and easiest way to accomplish this?
If this is Bootstrap then your partial view's modal HTML is broken. modal-body and modal-footer are under modal-header. I'm pretty sure modal-header, modal-body and modal-footer needs to be direct children of modal-content and that needs to child of modal-dialog and that needs to be child of modal and you have those container divs there wrapping them.
Edit:
Your problem is that you are loading your jquery and bootstrap after you try to use them. That <script> is run before your scripts are loaded. You need to put that into scripts section.
Camilo Terevinto notice you need remove jQuery script tag from your view. You already have jQuery in a bundle.
"When I click the button as seen in the image above. Nothing happens. " -> I have just tried your code and it works, modal is openning. Has Camilo Terevinto comment you should press 12 in chrome, and check for errors in console tab.
After modal open, what is missing in your code?
Use "Person" model in modal, create a post form and set button ok to submit
#model Person //Should contain person model namespace
#Html.BeginForm("PartialViewTest", "Home", FormMethod.Post)
{
<div class="container">
<div class="row">
<div class="col-sm-4"></div>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModal-label">Bootstrap Dialog</h4>
<div>
<div class="modal-body">
<div class="form-group">
#Html.TextBoxFor(p => p.name)
</div>
<div class="form-group">
#Html.TextBoxFor(p => p.adress)
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btnOK" onclick="">OK</button>
<button class="btn btn-default" data-dismiss="modal" id="btnCancel">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Your post action should redirect to Index.
[HttpPost]
public ActionResult PartialViewTest(Person person)
{
/* do things */
return RedirectToAction("Index");
}

Submitting a form from a partial view

I'm trying to submit a form from a modal generated in a partial view. And I don't know how to get back the submitted form.
Here is the view:
#model Myproject.ViewModels.GetMonitorFromDeviceViewModel
#{
ViewBag.Title = "GetMonitorFromDevice";
Layout = "~/Views/Shared/ManagementPage.cshtml";
}
<div id="Accordion">
#{
foreach (var type in Model.AvailableTypesAvailableMonitors)
{
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" data-parent="#accordion" href="##type">
#type
</a>
</div>
<div id="#type" class="collapse show">
<div class="card-body">
#{
foreach (var monitor in Model.ActiveMonitors)
{
if (monitor.Type == #type)
{
<p>
#monitor.Name
<span class="btn btn-xs btn-primary btnEdit" onclick="createModal('#Url.Action("NameMonitor", "DeviceManager" , new { idDevice = monitor.DeviceOwner.ID, monitorName = monitor.Name })')">Details</span>
</p>
}
}
}
</div>
</div>
</div>
}
}
</div>
And here is my modal at the bottom of the page:
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content" id="modelContent">
</div>
</div>
</div>
<script>
function createModal(url) {
$('#modelContent').load(url);
$('#myModal').modal('show');
}
</script>
And finally, here is my partial view that is displayed as a modal:
#model MyProject.ViewModels.NameMonitorModal
#using (Html.BeginForm("NameMonitor", "DeviceManager", FormMethod.Post))
{
<div class="modal-body">
<div class="form-group">
#Html.LabelFor(model => model.NewName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewName, new { htmlAttributes = new { #class = "form-control", #Value = Model.TrueName } })
#Html.ValidationMessageFor(model => model.NewName, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(model => model.TrueName)
#Html.HiddenFor(model => model.IdDevice)
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save name" class="btn btn-default" data-dismiss="modal" />
</div>
</div>
</div>
}
In my controller, I have an action for my partial view called ActionResult NameMonitor.
In order to catch the submited form, I tried to add another action with the [HttpPost] tag with the same name but doesn't work. I also tried to use the main page action with the [HttpPost] tag but it doesn't work either. As you can see, I have specified the action and controller in the form itself but its still not working.
Now, I'm a little bit out of idea of how I can get the information from my modal back.
data-dismiss="modal" will close the modal without submitting the form, see Dismiss and submit form Bootstrap 3
You can change the submit button to call a JavaScript function to submit the form, then close the modal.
function submitModal() {
$('#myFormId').submit();
$('#myModal').modal('hide');
}

Partial view that does not use the ActionName that I specify

I am currently developing an application in C # with ASP.NET MVC and entity Framework.
I use a partialview to edit data, for example I have a list of "module" in table form, I can add a module, delete one or edit one.
To create a module I proceed as follows:
My view :
<asp:UpdatePanel ID="ModuleUpdatePanel" runat="server">
<ContentTemplate>
<!-- Modal -->
<asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
<div class="modal fade" id="ModuleModal" tabindex="-1" role="dialog" aria-labelledby="ModuleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
#Html.Action("_CreateModule")
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The controller's method returning the partialview inside my modal:
[Authorize]
public ActionResult _CreateModule()
{
ModuleViewModel ViewModel = new ModuleViewModel { };
return PartialView(ViewModel);
}
The partialview :
#using (Html.BeginForm("CreateModule", "Parametres", FormMethod.Post))
{
#model Lynx.ViewModels.ModuleViewModel
<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="ModuleModalLabel">
Ajouter un module
</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.TextBoxFor(m => m.Module.Libelle_Module, new { #class = "form-control", #placeholder = "Libellé du module" })
#Html.ValidationMessageFor(m => m.Module.Libelle_Module)
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Module.Capacite_Max_Module, new { #class = "form-control", #placeholder = "Capacité max (Palettes/heure)" })
#Html.ValidationMessageFor(m => m.Module.Capacite_Max_Module)
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Annuler
</button>
<input type="submit" class="btn btn-success" value="Enregistrer" />
</div>
}
The controller's method adding the module:
[Authorize]
[ActionName("CreateModule")]
public void CreateModule(Modules module)
{
if (ModelState.IsValid)
{
if (Dal.GetModule(module.PK_Code_Module) == null)
{
Dal.AddModule(Dal.GetMaxIdModule() + 1, module.Libelle_Module, module.Capacite_Max_Module);
}
}
}
For this part, everything works. Where I have a problem is at the level of my module edition (I use the same process)
View :
<div class="modal-content">
#Html.Action("_EditModule", "Parametres", new { id = #module.PK_Code_Module })
</div>
The controller's method returning the partialview inside my modal:
[Authorize]
public ActionResult _EditModule(int Id)
{
Modules module = Dal.GetModule(Id);
return PartialView(module);
}
The PartialView :
#using (Html.BeginForm("EditModule", "Parametres", FormMethod.Post))
{
#model Lynx.Models.Modules
<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="EditModuleModalLabel">
Modifier un module
</h4>
</div>
<div class="modal-body">
<div>
<b>Id Module</b>
#Html.TextBoxFor(model => model.PK_Code_Module, new { #class = "form-control", #readonly = "readonly" })
</div>
<div>
<b>Libellé</b>
#Html.TextBoxFor(model => model.Libelle_Module, new { #class = "form-control" })
</div>
<div>
<b>Capacité max du module (colis/heure)</b>
#Html.TextBoxFor(model => model.Capacite_Max_Module, new { #class = "form-control" })
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Annuler
</button>
<input type="submit" class="btn btn-success" value="Enregistrer" />
</div>
}
The controller's method Editing the module:
[Authorize]
[ActionName("EditModule")]
public void EditModule(Modules module)
{
if (Dal.GetModule(module.PK_Code_Module) != null)
{
Dal.UpdateModule(int.Parse(module.PK_Code_Module), module.Libelle_Module, module.Capacite_Max_Module);
}
String URL = HttpContext.Request.Url.AbsoluteUri;
string[] lines = Regex.Split(URL, "/");
if (lines[lines.Length - 1] == "Parametres")
{
Response.Redirect("Parametres");
}
else
{
Response.Redirect("Index");
}
}
Here my button "Enregistrer" does absolutely nothing ... As if he ignored my "Bginform"
Any ideas ?
Put [HttpPost] in the action on your controller. Like that:
[HttpPost]
[Authorize]
[ActionName("EditModule")]
public void EditModule(Modules module)
{
if (Dal.GetModule(module.PK_Code_Module) != null)
{
Dal.UpdateModule(int.Parse(module.PK_Code_Module), module.Libelle_Module, module.Capacite_Max_Module);
}
String URL = HttpContext.Request.Url.AbsoluteUri;
string[] lines = Regex.Split(URL, "/");
if (lines[lines.Length - 1] == "Parametres")
{
Response.Redirect("Parametres");
}
else
{
Response.Redirect("Index");
}
}

Partial View Not Rendering Inside View

I have a partial view inside another partial view which, when first running the application loads as expected, but when you click to reload the view to push a model into it, it then renders as it's own completely separate view as if it weren't a partial.
I'm calling it inside an Ajax Form like so (On the Action link click, the _GetSearchModal method):
<div id="modelSearch">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<i class="fa fa-search"></i> Search by Model / Manufacturer
</h3>
</div>
<div class="panel-body">
#using (Ajax.BeginForm("_GetSearch", "Home", new AjaxOptions() {UpdateTargetId = "modelSearch"}))
{
#Html.AntiForgeryToken()
<div class="input-group">
#Html.TextBox("search", null, new {id = "name", #class = "form-control", placeholder = "Please enter a manufacturer or model"})
<span class="input-group-btn">
<button id="search" class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
if (Model != null)
{
<div id="searchResults" class="fade-in two">
#foreach (var s in Model)
{
<div class="result">
#switch (s.ResultType)
{
case "Man":
#s.Manufacturer
break;
case "Mod":
#Html.ActionLink(s.Manufacturer + Html.Raw(s.Model), "_GetSearchModal", "Home", new {id = s.MachineId}, new {toggle = "modal", data_target = "#MachineModal"})
<img src="~/Images/General/Tier/#(s.TierId).png" alt="Tier #s.TierId"/>
break;
}
</div>
}
</div>
}
}
</div>
</div>
</div>
<!-- Product Modal -->
<div class="modal fade" id="MachineModal" tabindex="-1" role="dialog" aria-labelledby="MachineModalLabel">
#Html.Partial("_SearchModal", new MachineModal())
</div>
And the view itself should load a different view model (MachineModal):
#model SpecCheck.Portals.Web.UI.ViewModels.MachineModal
#if (Model != null)
{
<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="MachineModalLabel">#Model.Manufacturer #Model.Model</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<img src="~/Images/#Model.Manufacturer/logo.png" alt="#Model.Manufacturer" /><br />
Wiki
</div>
<div class="col-md-6">
#Model.Catagory1 | #Model.Category2<br /><br />
<span class="modal-em">Region: </span> #Model.Region<br />
<span class="modal-em">Status: </span>#Model.Status<br />
<span class="modal-em">Spec Date: </span>#Model.SpecDate
</div>
</div>
</div>
<div class="modal-footer">
View
Quick Compare
Compare
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
}
And the action to do this in the "Home Controller" is:
public ActionResult _GetSearchModal(string machineId)
{
using (var db = new SpecCheckDbContext())
{
MachineModal machine = new MachineModal();
var searchHelper = new SearchHelper(db);
//Get Machine Details
var dbResults = searchHelper.SearchModal(Convert.ToInt32(machineId));
machine.Model = dbResults.Model;
machine.Catagory1 = dbResults.Catagory1;
machine.Category2 = dbResults.Category2;
machine.Manufacturer = dbResults.Manufacturer;
machine.Region = dbResults.Region;
machine.SpecDate = dbResults.SpecDate;
machine.Status = dbResults.Status;
machine.MachineId = dbResults.MachineId;
machine.ManufacturerId = dbResults.ManufacturerId;
var model = machine;
return PartialView("_SearchModal", model);
}
}
First thing I checked was the scripts, they're all in place when the layout page loads so it's not a script issue. Not sure what to change to even try at this point so any suggestions welcome.
In the ajax form:
_GetSearch => _GetSearchModal(name of the action)
Try to return machine to the partial view? Maybe see in the View hierarchy, is there is second _SearchModal partial view, that gets returned?

Categories