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
}
Related
Even though the model is not null the required html is not rendered. This is my razor view:
#model List<Product>
#{
ViewBag.Title = "Cart";
}
#for(int i=0;i<=Model.Count()-1;i++)
{
<p>foreach triggered</p>
var image = "~/images/" + Model[i].product_image_path;
<div class="row">
<div class="col">
<div class="row">
<div class="col-md-2">
<img src="#image" alt="No image" class="img-fluid" width="60" asp-append-version="true" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col">
<p class="justify-content-md-start">#Model[i].ProductName</p>
</div>
</div>
<div class="row">
<div class="col">
<p>₹#Model[i].Price</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-8">
#*change quantity button*#
<div class="input-group">
<button type="submit" class="btn btn-light"> - </button>
<input type="text" class="form-control" value="#Model[i].Quantity" readonly />
<button type="submit" class="btn btn-light"> + </button>
</div>
</div>
</div>
<br />
</div>
<div class="col-md-2">
<div class="row">
<div class="col">
<button class="btn btn-danger" type="button" id="button-minus">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Here is my get action method. This is basically retrieving the product from the models. I am returning an object of List<Product>. Trying to loop over it using for loop on razor view does not seem to work.
[HttpGet]
public IActionResult Cart()
{
var model = new CartProductViewModel();
var sessionId = HttpContext.Session.Id;
var allCartItems = context.cartItems;
var allProducts = context.products;
var currentCartItem = allCartItems.Where(p => p.Product.ProductId.Equals(sessionId)).Select(p=>p).ToList();
List<Product> products = new List<Product>();
foreach (var item in currentCartItem)
{
var id = item.Product.ProductId;
if (id is null) { return View("NotFound"); }
Product prod = allProducts.Where(p => p.ProductId.Equals(id)).Select(p=>p).Single();
products.Add(prod);
}
return View(products);
}
i Have problem when i try the model validation by trying to fill the form by false.
And when i try to submit with the wrong value (not valid by model validator) it redirects to the page (without model).
Here's the screenshot :
Customer Index
redirect to Customer Create Page when i submit
Here's the code
CONTROLLER
//POST CREATE
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Models.Customer obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//GET DELETE
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var obj = _db.Customers.Find(id);
if (obj == null)
{
return NotFound();
}
return PartialView(obj);
}
Model
public class Customer
{
[Key]
public int Id { get; set; }
[DisplayName("Nama Customer")]
[Required]
[MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
public string Nama { get; set; }
public string Alamat { get; set; }
[Phone]
[Required]
public string Telp { get; set; }
}
Index.HTML Button Create
<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>
JS
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
CREATE CSHTML
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-4">
<h2 class="text-black-50 pl-3">Add Customer</h2>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
#*validasi form*#
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-6">
</div>
<div class="col-6">
</div>
<div class="col-6">
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you (:
And when i try to submit with the wrong value (not valid by model
validator) it redirects to the page (without model).
You use return View(obj); when modelstate is not valid. So it will return view with model and the view name should be the action name(Create) if you do not specific view name. So this result is correct by using your code.
Here is a working demo:
Index.cshtml:
<button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
<div class="modal fade" id="modalCustomer" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
//$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
</script>
}
Create.cshtml:
#model Customer
#{
Layout = null; //be sure add this...
}
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
#*change here..........*#
<input type="button" id="btn" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
JS in Create.cshtml:
<script>
$(document).on('click', '#modalCustomer #btn', function () {
var options = {};
options.type = "POST";
options.url = "/Customer/create";
options.dataType = "JSON";
options.cache = false;
options.async = true;
options.data = $("form").serialize();
options.success = function (data) {
//do your stuff...
$('#modalCustomer').modal('hide');
//if you don't want to stay in Index
//add the following code..
// window.location.href = "/home/privacy";
};
options.error = function (res) {
$('#modalBody').html(res.responseText);
};
$.ajax(options);
});
</script>
Update:
If modelstate is invalid, it will get into options.error and display the error message in modal. If modelstate is valid, it will get into options.success, you could redirect by using window.location.href or hide the modal by $('#modalCustomer').modal('hide');, just do your stuff.
Backend code should be like below:
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Customers obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return Json(new { success = true }); //change this...
}
return View(obj);
}
I am posting form data to my controller using AJAX, the form is located in a partial view which is called and displayed in a modal. When first submit the form to update my data it works fine, then if I post it again I notice in the console log that it posts the data twice, if I post it again, it posts three times, and so on. The only way to prevent that behavior is to refresh the page.
Here is the code for my partial view.
#model UserView
<div class="modal fade" id="edit-custom-view" tabindex="-1" role="dialog" aria-labelledby="edit-custom-view" aria-modal="true">
<div class="modal-dialog modal-dialog-scrollable modal-lg modal-notify modal-primary" role="document">
<div class="modal-content">
<form id="ModalFormEditCustomView" enctype="multipart/form-data">
<div class="modal-body">
<div class="row">
<input type="text" asp-for="Id" hidden readonly />
<div class="col">
<div class="md-form form-group">
<label asp-for="ViewName">View Name</label>
<input type="text" required class="form-control" asp-for="ViewName" />
</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" data-save="edit-view" class="btn btn-info waves-effect waves-light">Update</button>
<button type="button" class="btn btn-secondary waves-effect waves-light" data-dismiss="modal">Close</button>
</div><!--/modal-footer-->
</form>
</div>
</div>
</div>
My function that posts the data. Please note, placeholderElement is a div that is the modal window.
placeholderElement.on('click', '[data-save="edit-view"]', function (event) {
//Prevent the standard behaviour
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl , dataToSend).done(function (data) {
var newBody = $('.modal-body', data);
placeholderElement.find('.modal-body').replaceWith(newBody);
placeholderElement.find('.modal').modal('hide');
});
});
Here is my controller
[HttpPost]
public JsonResult EditCustomView(UserView model) {
... update code goes here
return Json(model);
}
This is the button that opens the modal with the form in it.
<button data-view-id='#=Id#' onclick='editViewModal(this, event)' data-area='Home' data-context='Position' data-toggle='ajax-modal' data-target='#edit-custom-view' data-action='EditCustomView' data-url='/Home/EditViewModal/'>Button</button>
And finally, the code that opens the modal and fetches the partial view.
public IActionResult EditViewModal(int id)
{
string partial = "_EditCustomView";
UserView userView = _userViewService.GetUserView(id);
return PartialView(partial, userView);
}
So, when I click on submit, the ajax function is triggered to submit the data, and the modal closes. If I edit the same item again without refreshing the page, the form gets submitted twice and so on, adding an additional post-event each time. My question is, why? I can't see any reason as to why it would do this. Any help is appreciated.
I cannot reproduce your problem since the code you provided is not complete. Maybe you can show us the placeholderElement and the scripts of editViewModal(this, event) function in the button click event.
Besides, in your case, we can call and display the a modal in the following way.
Here is a work demo:
Model:
public class UserView
{
public int Id { get; set; }
public string ViewName { get; set; }
public string Address { get; set; }
public string Tel { get; set; }
}
Partial View:
#model UserView
<div class="modal fade" id="edit-custom-view" tabindex="-1" role="dialog" aria-labelledby="edit-custom-view" aria-modal="true">
<div class="modal-dialog modal-dialog-scrollable modal-lg modal-notify modal-primary" role="document">
<div class="modal-content">
<form id="ModalFormEditCustomView" data-action="/Home/EditCustomView" enctype="multipart/form-data">
<div class="modal-body">
<div class="row">
<input type="text" asp-for="Id" hidden readonly />
<div class="col">
<div class="md-form form-group">
<label asp-for="ViewName">View Name</label>
<input type="text" required class="form-control" asp-for="ViewName" />
</div>
<div class="md-form form-group">
<label asp-for="Address">Address</label>
<input type="text" required class="form-control" asp-for="Address" />
</div>
<div class="md-form form-group">
<label asp-for="Tel">Tel</label>
<input type="text" required class="form-control" asp-for="Tel" />
</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" data-save="edit-view" class="btn btn-info waves-effect waves-light">Update</button>
<button type="button" class="btn btn-secondary waves-effect waves-light" data-dismiss="modal">Close</button>
</div><!--/modal-footer-->
</form>
</div>
</div>
</div>
Edit View:
#model UserView
<div class="row">
<div class="col-md-4">
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="ViewName" class="control-label"></label> :
<input asp-for="ViewName" class="form-control" readonly />
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label> :
<input asp-for="Address" class="form-control" readonly />
</div>
<div class="form-group">
<label asp-for="Tel" class="control-label"></label> :
<input asp-for="Tel" class="form-control" readonly />
</div>
<div class="form-group">
<button name="btn" value="#Model.Id" class="btn btn-primary">Edit</button>
</div>
</div>
</div>
<div id="placeholderElement">
</div>
#section Scripts
{
<script>
$(".btn.btn-primary").on("click", function () {
var id = $(this).val();
$.ajax({
type: "get",
url: "/Home/EditViewModal?id=" + id,
success: function (result) {
$("#placeholderElement").html(result);
$("#edit-custom-view").modal('show');
}
});
})
$("#placeholderElement").on('click', '[data-save="edit-view"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.data('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$("#placeholderElement").find('.modal').modal('hide');
$("#ViewName").val(data.viewName);
$("#Address").val(data.address);
$("#Tel").val(data.tel);
});
});
</script>
}
Controller:
public IActionResult Edit()
{
var model = _db.UserViews.Find(1);
return View(model);
}
public IActionResult EditViewModal(int id)
{
string partial = "_EditCustomView";
var userView = _db.UserViews.Find(id);
return PartialView(partial, userView);
}
[HttpPost]
public JsonResult EditCustomView(UserView model)
{
var model1 = _db.UserViews.Find(model.Id);
model1.ViewName = model.ViewName;
model1.Address = model.Address;
model1.Tel = model.Tel;
_db.Update(model1);
_db.SaveChanges();
return Json(model1);
}
Where is this script located? If it is inside of the partial that is what is causing the issue for you. Every time the partial is pulled in an extra event is attached to the element.
This would cause the behavior that you are describing.
Hey so I have a modal popup form where I have to upload files and post data to the database. In the controller I'm retrieving the values by FormCollection. When I try to get the input fields with form collection i get this error : Can not implicitly convert System.Windows.Forms.Form to 'String'. Here is my code:
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection formCollection, HttpPostedFileBase upload, AAC_procedure_document_types model,NgarkoDokument ngarkoDok)
{
try
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var file = new AAC_procedure_documents
{
Emer_Dokumenti = System.IO.Path.GetFileName(upload.FileName),
Lloji_File = model.Emri_llojit,
Content_Type = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Permbajtje_Dokumenti = reader.ReadBytes(upload.ContentLength);
}
ngarkoDok.AAC_procedure_documents = new List<AAC_procedure_documents> { file };
}
AAC_procedure_documents_location lokacion = new AAC_procedure_documents_location();
lokacion.Rafti = formCollection["Rafti"];
lokacion.Zyra = formCollection["Zyra"].ToString();
lokacion.Nr_Kutise = Convert.ToInt32(formCollection["Nr_Kutise"]);
db.AAC_procedure_documents_location.Add(lokacion);
db.SaveChanges();
return RedirectToAction("Dokumenti");
}
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(formCollection);
}
Html form
<div id="myModal" 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">Ngarkoni dokumenta</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Create", "NgarkoDokument", FormMethod.Post, new { enctype = "mulptiple/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<label for="exampleFormControlSelect1">Lloji i dokumentit</label><br />
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
<input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
<input type="file" onchange="javascript: updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles" />
<div id="fileList"></div>
</div>
<br /><br />
<div class="form-group">
<label for="formGroupExampleInput">Fusha indeksimi</label> <br />
#*<input title="Indeksimi dokumentit" id="indeksimi" class="form-control col-md-3" type="text" name="indeksimi" placeholder="indeksimi" required />*#
#Html.TextBoxFor(a => a.Fusha_Indeksimit.Emri_Indeksimit, new { #class = "form-control", #placeholder = "indeksimi" })
<button title="Shto indeksim" id="modalPlus" type="submit" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i></button>
</div>
<label for="formGroupExampleInput">Vendndodhja fizike e dokumentit</label><br>
<div id="zyraModal" class="form-group col-md-4">
#*<input title="Zyra fizike" id="zyra" class="form-control" type="text" name="zyra" placeholder="Zyra" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Zyra, new { #class = "form-control", #placeholder = "Zyra" })
</div>
<div class="form-group col-md-4">
#* <input title="Kutia fizike" id="kutia" class="form-control" type="number" name="kutia" placeholder="Nr i kutisë" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Nr_Kutise, new { #class = "form-control", #placeholder = "Nr i kutisë" })
</div>
<div class="form-group col-md-4">
#* <input title="Rafti fizik" id="rafti" class="form-control" type="text" name="rafti" placeholder="Rafti" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Rafti, new { #class = "form-control", #placeholder = "Rafti" })
</div>
<br /><br />
<div class="row" id="ruaj">
<button value="Create" title="Ruaj dokumentin" type="submit" class="btn btn-success">Ruaj</button>
</div>
}
</div>
</div>
The namespace to FormCollection must to be System.Web.Mvc instead of System.Windows.Forms. Take a look in your usings and remove System.Windows.Forms...
The class FormCollection exists in two tecnologies, WindowsForm and Web.
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