Show <select> values in PartialView ASP.NET Core - c#

I migrate project from ASP.NET MVC to ASP.NET Core
I was having Partial view with two daropdowns
So Controller method was like this
public ActionResult AddPeopleToProposal()
{
ViewBag.Worker = new SelectList(db.People, "Id", "FIO").ToList();
ViewBag.Proposal = new SelectList(db.Proposals, "Id", "Id").ToList();
return PartialView("AddPeopleToProposal");
}
And in View I was render it like this
<div class="modal fade" id="addPeopleToProposal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Добавить работника на заявку</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.Action("AddPeopleToProposal", "Manage")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Отмена</button>
<button type="button" id="peopleToProposalCreate" class="btn btn-primary">Создать</button>
</div>
</div>
</div>
And Partial View
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Працівник</label>
#Html.DropDownList("Worker", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "peopleIdAdd" })
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Оберіть заявку</label>
#Html.DropDownList("Proposal", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "proposalIdAdd" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Коментар</label>
<input type="text" class="form-control" id="commentVchasno" >
</div>
But as I know #Html.Action was depricated
I realize this in Core like this
Controller
public ActionResult AddPeopleToProposal()
{
ViewData["Worker"] = new SelectList(_context.People, "Id", "FIO");
ViewData["Proposal"] = new SelectList(_context.Proposals, "Id", "Id");
return PartialView("Partials/AddPeopleToProposal");
}
And Partial View
<form>
<div class="form-group">
<label class="col-form-label">Працівник</label>
<select class="form-control" asp-items="ViewBag.Worker"></select>
</div>
<div class="form-group">
<label class="col-form-label">Оберіть заявку</label>
<select class="form-control" asp-items="ViewBag.Proposal"></select>
</div>
<div class="form-group">
<label class="col-form-label">Коментар</label>
<input type="text" class="form-control" id="commentVchasno" >
</div>
</form>
And View from where I cal Partial
<div class="modal fade" id="addPeopleToProposal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Добавить работника на заявку</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.Partial("Partials/AddPeopleToProposal")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Отмена</button>
<button type="button" id="peopleToProposalCreate" class="btn btn-primary">Создать</button>
</div>
</div>
</div>
But at Core I don't have values in selects. Where is my problem?

If you want to initialize the page directly when getting the Partial View, try to put the following two lines of code into the get request of the main View of the Partial View. More about Partial views
ViewData["Worker"] = new SelectList(_context.People, "Id", "FIO");
ViewData["Proposal"] = new SelectList(_context.Proposals, "Id", "Id");
Or you could use the ViewComponent instead of the Partial View to get the fill data of the dropdownlists from the Invoke method in the view component class. Try to the code like below
ViewComponent.cs
public class AddPeopleToCountryViewComponent:ViewComponent
{
private readonly MVCDbContext _context;
public AddPeopleToCountryViewComponent(MVCDbContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
ViewData["Customer"] = new SelectList(_context.Customer, "Id", "Name");
ViewData["Country"] = new SelectList(_context.Country, "Id", "Id");
return View();
}
}
The Default.cshtml of ViewComponent
<form>
<div class="form-group">
<label class="col-form-label">People</label>
<select class="form-control" asp-items="#ViewBag.Customer"></select>
</div>
<div class="form-group">
<label class="col-form-label">Country</label>
<select class="form-control" asp-items="#ViewBag.Country"></select>
</div>
<div class="form-group">
<label class="col-form-label">Comment</label>
<input type="text" class="form-control" id="commentVchasno">
</div>
Instead of the PartialView in the modal of the main view
<div class="modal-body">
#await Component.InvokeAsync("AddPeopleToCountry", new { })
</div>

Related

Asp Net Core 2 Models in one page Validation

To be short, I have 2 View Models, one is for creating and another for editing. The problem is to bypass ModelState validation for one of them. For example, I want to edit a user. When I post it will say validation is invalid for the Input Model which I do not want to use when I trigger the OnPostEdit handler. I tried to remove the key from ModelState but does not work because using debugger all the properties appear without the class which means I would have to remove all properties one by one by their names. The point is, how can I handle all of this without having to remove keys one by one? I know I could just create another page but it's better UX to have it all on one.
Also I found a similar post but has no solution, but should explain what I need better too.
Razor Pages - Model validation fails due to multiple objects sharing parameters
#if (Model.EditInput != null)
{
<form method="post" asp-page-handler="Edit">
<!-- Modal -->
<div class="modal fade" id="modalEditUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header bg-warning">
<h5 class="modal-title" id="exampleModalLabel"><i class="fas fa-edit"></i> Editar Utilizador</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><i class="fas fa-times"></i></span>
</button>
</div>
<div class="modal-body">
<input type="hidden" asp-for="EditInput.Id" />
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="EditInput.UserName"></label>
<input asp-for="EditInput.UserName" class="form-control rounded-0" />
<span asp-validation-for="EditInput.UserName" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="EditInput.Name"></label>
<input asp-for="EditInput.Name" class="form-control rounded-0" />
<span asp-validation-for="EditInput.Name" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="EditInput.Email"></label>
<input asp-for="EditInput.Email" class="form-control rounded-0" />
<span asp-validation-for="EditInput.Email" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="EditInput.Password"></label>
<input asp-for="EditInput.Password" class="form-control rounded-0" />
<span asp-validation-for="EditInput.Password" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="EditInput.ConfirmPassword"></label>
<input asp-for="EditInput.ConfirmPassword" class="form-control rounded-0" />
<span asp-validation-for="EditInput.ConfirmPassword" class="text-danger"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-warning">Guardar</button>
</div>
</div>
</div>
</div>
</form>
}
<form method="post">
<!-- Modal -->
<div class="modal fade" id="modalAddUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header bg-lightblue">
<h5 class="modal-title" id="exampleModalLabel">Adicionar Artigo a Kit</h5>
<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><i class="fas fa-times"></i></span>
</button>
</div>
<div class="modal-body">
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Input.UserName"></label>
<input asp-for="Input.UserName" class="form-control rounded-0" />
<span asp-validation-for="Input.UserName" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Input.Name"></label>
<input asp-for="Input.Name" class="form-control rounded-0" />
<span asp-validation-for="Input.Name" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control rounded-0" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control rounded-0" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control rounded-0" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn bg-lightblue">Adicionar</button>
</div>
</div>
</div>
</div>
</form>
Page Model
[BindProperty]
public EditUserVM EditInput { get; set; }
[BindProperty]
public UserVM Input { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
GetData();
_toast.AddErrorToastMessage("Dados inválidos.");
return Page();
}
// add user
_toast.AddSuccessToastMessage("Utilizador alterado.");
return RedirectToPage("Index");
}
public async Task<IActionResult> OnPostEditAsync()
{
ModelState.Remove(nameof(UserVM));
if (!ModelState.IsValid)
{
GetData();
_toast.AddErrorToastMessage("Dados inválidos.");
return Page();
}
var user = await _userManager.FindByIdAsync(EditInput.Id.ToString());
user.UserName = EditInput.UserName;
user.Name = EditInput.Name;
user.Email = EditInput.Email;
user.IsBlocked = EditInput.IsBlocked;
user.ModifiedAt = DateTime.Now;
var hashedPassword = _userManager.PasswordHasher.HashPassword(user, EditInput.Password);
user.PasswordHash = hashedPassword;
await _userManager.UpdateAsync(user);
_toast.AddSuccessToastMessage("Utilizador alterado.");
return RedirectToPage("Index");
}
So the solution is to wrap both models into one
For example instead of having this
[BindProperty]
public EditUserVM EditInput { get; set; }
[BindProperty]
public UserVM Input { get; set; }
I would create another class in my page and change the properties around the page accordingly. With this If I hit the Edit Handler, the UserVM won't appear on the ModelState and the same vice-versa
[BindProperty]
public FormModel Form { get; set; }
public class FormModel
{
public UserVM Input { get; set; }
public EditUserVM EditInput { get; set; }
}

Modal Dialog No Redirect

I use C# MVC version 5. I have a form in a modal dialog, which uses a partial view. I want to submit the form and not redirect. I just want the dialog to close. Can this be done?
Here is my code:
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">#title</h5>
</div>
#using (Html.BeginForm("Edit", "Region", FormMethod.Post, new { onsubmit = "return validateForm();", #class = "form-horizontal" }))
{
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Submit form</button>
</div>
}
</div>
</div>
public ActionResult Edit(int id)
{
RegionViewModels regionViewModels = MakeRegionViewModels(id);
return PartialView("_InsertTaxRegion", regionViewModels);
}
With jQuery you can just serialize the form data and send it to the server in the background and you can close your modal, here is an example:
How to use jquery $.post() method to submit form values
If you are using <input type="submit" /> instead of <button type="button">Submit</button> then you'll need to prevent your form from submitting like this:
Using JQuery - preventing form from submitting
You can do this with a Bootstrap modal without the jQuery code.
On the page where I want to display the modal. Your modal form (PartialView) will display on top of the view you're already on.
<button id="btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data- target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog" data-toggle="modal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#Html.Partial("Modal");
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
Your modal displays in a PartialView...
#model NCR.Models.Employee
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.FIRST_NAME, htmlAttributes:
new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FIRST_NAME,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FIRST_NAME, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LAST_NAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LAST_NAME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LAST_NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
}

Validate multiple Partial view without BeginForm in a View

I have a View (Index.cshtml) that it has two modals (Bootstrap modal).
I have loaded a Partial View in each ‍‍‍modal. So in this View, I have two Partial Views(AddContractHistory.cshtml and AddCompany.cshtml).
I have a model that it's fields should be validated in each of the Partial Views.
I need to validate each of the partial views separately.
In same other issue, Html.BeginForm was used but I work on MVC module and DNN 8 that Html.BeginForm or Ajax.Html.BeginForm aren't supported.
For doing this work without having BeginForm, I tested many ways like below but I couldn't do it properly.
ASP.NET MVC Validation Groups?
ASP.NET MVC Multiple form in one page: Validation doesn't work
Index.cshtml (View)
#using MyProject.BusinessLogic
<div class="form-group">
<div class="col-sm-12">
<button type="button" class="btn btn-success" onclick="$('#AddContractHistory').modal('show');">
<i class="fa fa-plus"></i>
New ContractHistory
</button>
</div>
<div class="col-sm-12">
<button type="button" class="btn btn-success" onclick="$('#AddCompany').modal('show');">
<i class="fa fa-plus"></i>
New Company
</button>
</div>
</div>
<div id="AddContractHistory" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg" id="mymodal">
#Html.Partial("AddContractHistory", new ContractHistory())
</div>
</div>
<div id="AddCompany" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg" id="mymodal">
#Html.Partial("AddCompany", new Company())
</div>
</div>
AddContractHistory.cshtml (PartialView)
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<MyProject.BusinessLogic.ContractHistory>
<div id="myform">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">contract</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="panel-body">
<div class="form-horizontal">
#Html.ValidationSummary()
#Html.HiddenFor(c => c.ID)
<div class="form-group">
<div class="col-sm-6">
#Html.LabelFor(c => c.PlaceName)
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
</span>
#Html.EditorFor(c => c.PlaceName, new { htmlAttributes = new { #class = "form-control requierd-field" } })
</div>
</div>
<div class="col-sm-6">
#Html.LabelFor(c => c.ActivityDescription)
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
</span>
#Html.EditorFor(c => c.ActivityDescription, new { htmlAttributes = new { #class = "form-control requierd-field" } })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" formaction="AddContractHistory">
submit
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">cancel</button>
</div>
</div>
</div>
AddCompany.cshtml (PartialView)
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<MyProject.BusinessLogic.Company>
<div id="myform">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Company</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="panel-body">
<div class="form-horizontal">
#Html.ValidationSummary()
#Html.HiddenFor(c => c.ID)
<div class="form-group">
<div class="col-sm-6">
#Html.LabelFor(c => c.PlaceName)
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
</span>
#Html.EditorFor(c => c.PlaceName, new { htmlAttributes = new { #class = "form-control requierd-field" } })
</div>
</div>
<div class="col-sm-6">
#Html.LabelFor(c => c.ActivityDescription)
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
</span>
#Html.EditorFor(c => c.ActivityDescription, new { htmlAttributes = new { #class = "form-control requierd-field" } })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" formaction="AddCompany">
submit
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">cancel</button>
</div>
</div>
</div>
Thanks in advance!
You can implement your Html.BeginForm, which it's not supported in Dotnetnuke, in another way.
1. Change your buttons attributes
You should change buttons, which cause posting data to actions, like below:
<button id="btnAddContractHistory" type="button" class="btn btn-success">
submit
</button>
<button id="btnAddCompany" type="submit" class="btn btn-success">
submit
</button>
2. Add events click for buttons
Two click events call for posing data to desire actions. In this events, which are different in url, action attribute form are changed by your url and after that form.submit() causes pass data (model) to related action. Finally you would validate values of properties in two different actions.
<script>
$('.modal').find('#btnAddContractHistory').on('click', function () {
var url = 'AddContractHistory action url'; // It depends on your AddContractHistory action url
var form = $(this).closest('form');
form.prop('action', url);
form.submit();
});
$('.modal').find('#btnAddCompany').on('click', function () {
var url = 'AddCompany action url'; // It depends on your AddCompany action url
var form = $(this).closest('form');
form.prop('action', url);
form.submit();
});
</script>
In general, I recommend you to integrate more JS code (JQuery ?) in your views. In that way you'll be less bounded to some framework (DNN) that doesn't support basic MVC functionality you're used to. After all - a web app boils down to HTML+JS+CSS, so the better JS knowledge you have - the better control and flexibility you gain.
Regarding your question, MVC injects JS code for you to handle validation errors upon submitting. You can imitate this behavior yourself. It'll take you some time, but you'll gain full control over this process.
When page is loaded (JS event), you can complete some work via JS, like wrapping your partial views with your desired <form> tag, and/or bind to the submit events.
As simple as that.
But regular form submission will refresh your page, loosing the other partial view data/state. So, if you need, you can post/get your data via AJAX (again JQuery?) and update your page accordingly.
<form data-reza-ajaxform="true"
data-reza-targetId="#your-htmlcontrol-id"
action="#Url.Action("Your Action")"
method="POST/GET">
<div class="input-group">
<input type="text" ...>
...
<button class="btn btn-default" type="submit">Go!</button>
</div>
</form>
Then, in your script you can do something like this:
$('form[data-reza-ajaxform]').on('submit', submitAjaxForm);
...
function submitAjaxForm(e) {
var $form = $(this);
var options = {
url: $form.action,
method: $form.method,
data: $form.serialize()
};
$.ajax(options)
.success(function(res) {
var $target = $($form.attr('data-reza-targetId'));
$target.html(res);
$target.effect('highlight', 'slow');
});
e.preventDefault();
}
In this way you'll gain full control over your page and its parts. No matter in which framework you'll will work with. What can be better? :)

Request is not receiving file - Asp.Net Mvc

I'm trying upload a file from my page, but the request is not receiving posted file.
My form is into a normal Bootstrap modal, and this is the view.
#model InventarioWeb.Mvc.ViewModels.InventarioViewModel
<!-- Modal -->
<div id="ImportadorModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Importar Arquivo</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("ImportarItensInventario", "Inventario", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-10">
#*<h4>Input Groups</h4>*#
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Procurar…
<input type="file"
id="fileToUpload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<span class="help-block">
Selecione um arquivo
</span>
</div>
<div class="col-md-10">
<input type="submit" id="SubmitArquivoInventario" name="Submit" value="Salvar Arquivo" class="btn btn-primary" disabled="disabled"/>
</div>
</div>
#*#Html.HiddenFor(x => x.InventarioId)*#
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And this is the controller's method
[HttpPost]
public ActionResult ImportarItensInventario(Guid inventarioId)
{
if (Request.Files["UploadInventarioItems"] == null || Request.Files["UploadInventarioItems"].ContentLength == 0)
{
return RedirectToAction(nameof(Details), new { id = inventarioId });
}
string path = $"{Server.MapPath("~/Uploads")}/{Request.Files["UploadInventarioItems"].FileName}";
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
Request.Files["UploadInventarioItems"].SaveAs(path);
var model = new InventarioViewModel {InventarioId = inventarioId};
var result = _arquivoAppService.ImportarArquivo(InventarioViewModel.ToModel(model), Request.Files["UploadInventarioItems"].FileName);
return RedirectToAction(nameof(Details), new { id = inventarioId});
}
When I request, the id parameter is received, but my file isn't.
Besides, the Request.Files does not have any item.
What I'm doing wrong??
Add name attribute to your input type file, you can workaround to get the file without this attribute, but it's more convenient.
<input type="file" id="fileToUpload" name="upload" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
and use in server this method to get the file:
if (Request.Files["upload"] == null || Request.Files["upload"].HasFile())
{
//do something
}
or like this for multiple files:
foreach (string inputTagName in Request.Files)
{
if (!Request.Files[inputTagName ].HasFile()) continue;
//... continue processing
}

Why is my Modal form posting a null model back to the controller

I have a partial view that I load in a Modal..in the index view the model div with the HTML.Partial
looks like this.
<div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modalEditDBInfoContent" style="background-color:white; border-radius:10px; box-shadow:10px;">
#Html.Partial("_EditDatabaseInfo")
</div>
</div>
</div>
the partial view code is
#model Hybridinator.Domain.Entities.Database
<br />
<br />
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModelTitle">Edit Database Info</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("EditDatabaseInfo", "Database", FormMethod.Post, new { #class = "modal-body" }))
{
<div class="form-group">
<div id="databaselabel" >#Html.LabelFor(m => m.database, "Database")</div>
<div id="databaseedit" >#Html.EditorFor(m => m.database)</div>
</div>
<div class="form-group">
<div id="databaseserverlabel" >#Html.LabelFor(m => m.database_server, "Database Server")</div>
<div id="databaseserveredit" >#Html.EditorFor(m => m.database_server)</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-inverse btn-primary" type="submit">Save</button>
</div>
}
</div>
If fire this controller successfully
[HttpPost]
public ActionResult EditDatabaseInfo(Database database)
{
string s = database.database;
//do other stuff
return RedirectToAction("Index");
}
Everything works fine up until I try to access the model in the controller post which should be passed into ActionResult method. The Model object is null
Object reference not set to an instance of an object.
anyone see what Im missing here?
You have to pass the model in Header from the view and from controller and in partialview too
lisk below
Please get look deeply in bold text and the text in between ** **
**#model Hybridinator.Domain.Entities.Database**
<div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modalEditDBInfoContent" style="background-color:white; border-radius:10px; box-shadow:10px;">
#Html.Partial("_EditDatabaseInfo", **Model** )
</div>
</div>
[HttpPost]
public ActionResult EditDatabaseInfo(Database database)
{
string s = database.database;
//do other stuff
// **you have to get the model value in here and pass it to index action**
return RedirectToAction(**"Index", modelValue**);
}
public ActionResult Index(**ModelClass classValue**)
{
//pass the model value into index view.
return View(**"Index", classValue**);
}
Change the Model in view, partial view and in action . Instead of passing entity model, create view model and pass it in view as well as partial view. consider the following
#model **DatabaseModel**
<div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modalEditDBInfoContent" style="background-color: white; border-radius: 10px; box-shadow: 10px;">
#Html.Partial("_EditDatabaseInfo", **Model**)
</div>
</div>
</div>
#model DatabaseModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModelTitle">Edit Database Info</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm( new { #class = "modal-body" }))
{
<div class="form-group">
<div id="databaselabel" >#Html.LabelFor(m => m.DatabaseName, "Database")</div>
<div id="databaseedit" >#Html.EditorFor(m => m.DatabaseName)</div>
</div>
<div class="form-group">
<div id="databaseserverlabel" >#Html.LabelFor(m => m.DatabaseServer, "Database Server")</div>
<div id="databaseserveredit" >#Html.EditorFor(m => m.DatabaseServer)</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-inverse btn-primary" type="submit">Save</button>
</div>
}
</div>
public class DatabaseModel
{
public string DatabaseName { get; set; }
public string DatabaseServer { get; set; }
}
As of my knowledge Database is a key word, because of that it is getting null

Categories

Resources