MVC, Edit View problem with getting existing data in form - asp.net-mvc

I got a problem when I create edit view. I run program, from index view and click on edit on some data.
Issuse is that Im getting empty form(I can save it to database normaly) but I want to see what I entered and than edit some parts of data and save it.
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact item = db.Contacts.First(x => x.ContactId == csvm.ContactId);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe = csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice;
item.NazivNaselja = csvm.NazivNaselja;
item.PostanskiBroj = csvm.PostanskiBroj;
item.KontaktBroj = csvm.KontaktBroj;
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id { get; set; }
}
And View
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<h2>Edit</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
.....
and scripts from View for Parent-Child dropdown lists
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
</script>

You didn't select existing data to edit form.
You need to load your DB data to viewmodel and pass your viewmodel to cshtml by return View(vm):
[HttpGet]
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
var item = db.Contacts.First(x => x.ContactId == Id);
var vm = new EditStateContactViewModel();
vm.Id = Id;
vm.NazivNaselja = item.NazivNaselja;
...
return View(vm);
}

Related

How to disable a textbox while when we hit edit option in edit.cshtml page in mvc?

====> Here is my edit.cshtml page code:
<div class="form-group">
#Html.LabelFor(model => model.Eno, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #class = "form-control" } } )
#Html.ValidationMessageFor(model => model.Eno, "", new { #class = "text-danger" })
</div>
</div>
I want to disable this textbox. Can anyone help me with that.
This is my Controller:
[HttpGet]
public ActionResult Edit(int id)
{
Models.Employee e1 = new Models.Employee();
e1.Eno = id;
e1 = objdalemp.SearchEmp(e1);
return View(e1);
}
[HttpPost]
public ActionResult Edit(Models.Employee e1)
{
int i = objdalemp.UpdateEmployee(e1);
if(i==1)
{
return RedirectToAction("Index");
}
return View(e1);
}
You can disable a html field generated using the following
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #class = "form-control", #disabled = "disabled" } }).
You can disable like below.
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #disabled ="true", #class = "form-control" } })

System.InvalidOperationException: 'The ViewData item that has the key 'X is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.'

I got this error when I want to Create my Contact. Need help I would be thankful.
My database SQL database table is connected via entity framework.
Home Controller / Create Action
[HttpGet]
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact()
{
CountryId = csvm.CountryId,
StateId = csvm.StateId,
ContactId = csvm.ContactId,
ImeOsobe = csvm.ImeOsobe
...and all other fields
};
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
Now here is ViewModel
public int CountryId { get; set; }
[Required]
[Display(Name = "Naziv županije")]
public string CountryName { get; set; }
public int StateId { get; set; }
[Required]
[Display(Name = "Naziv općine")]
public string StateName { get; set; }
public int ContactId { get; set; }
public virtual Country Country { get; set; }
public virtual State State { get; set; }
....and all other fields
And finally here is "Create" view.
#model AkvizicijeApp_4_7.Models.CountryStateContactViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new {
#class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label
col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class =
"form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger"
})
</div>
</div>
And after that is all other fields and js for parent/child dropdown list.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
Please help me solve my problem. <3

MVC- need help for creating "Edit" View

need help about creating Edit view. I made create view and I need to be able to edit my entry sometimes. I used entity framework for connect with sql.
```
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactId, ImeOsobe = csvm.ImeOsobe, PrezimeOsobe = csvm.PrezimeOsobe, Komentar = csvm.Komentar, Email = csvm.Email, Aktivan = csvm.Aktivan, kcbr = csvm.kcbr, KucniBroj = csvm.KucniBroj, NazivUlice = csvm.NazivUlice, NazivNaselja = csvm.NazivNaselja, PostanskiBroj = csvm.PostanskiBroj, KontaktBroj = csvm.KontaktBroj };
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
This is Create View where I am adding new Contact from CountryStateContactViewModel (All three tables in one VIEW with 2 connected dropdown lists )
#model AkvizicijeApp_4_2.Models.CountryStateContactViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostanskiBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostanskiBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostanskiBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivNaselja, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivNaselja, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivNaselja, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivUlice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivUlice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivUlice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KucniBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KucniBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KucniBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aktivan, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Aktivan)
#Html.ValidationMessageFor(model => model.Aktivan, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PrezimeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PrezimeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PrezimeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KontaktBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KontaktBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KontaktBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Komentar, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Komentar, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Komentar, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
And finally CountryStateContactViewModel, Where is id-s from first 2 tables(dropdowns) and all fields from third table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkvizicijeApp_4_2.Models
{
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public int ContactId { get; set; }
public int PostanskiBroj { get; set; }
public string NazivNaselja { get; set; }
public string NazivUlice { get; set; }
public string KucniBroj { get; set; }
public string kcbr { get; set; }
public bool Aktivan { get; set; }
public string ImeOsobe { get; set; }
public string PrezimeOsobe { get; set; }
public string KontaktBroj { get; set; }
public string Email { get; set; }
public string Komentar { get; set; }
}
}
Pls help me from that code (from Create View) to make Edit View (Where I can change entries
)
Thanks alot. ;)
Edit view is almost the same... the only missing property is Id:
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id {get;set;}
}
public ActionResult Edit(int Id)
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
return View(csvm);
var item = db.Contacts.First(x=>x.Id = csvm.Id);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe= csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar ;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan ;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice ;
item.NazivNaselja = csvm.NazivNaselja ;
item.PostanskiBroj = csvm.PostanskiBroj ;
item.KontaktBroj = csvm.KontaktBroj ;
db.Contacts.Update(item);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
And View:
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x=>x.Id)
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>

Another [Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'] in ASP.NET MVC

I tried to have a file upload into another folder, it works fine when it directly add to the database, but if I try to use it with MultipleDocumentCreateClass for the stored procedure, I get this error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
Controller
// GET: Activity/DocumentNew
public ActionResult DocumentNew(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Hoạt_động hoạt_động = db.Hoạt_động.Find(id); ;
ViewBag.act = hoạt_động;
if (hoạt_động == null)
{
return HttpNotFound();
}
MultipleDocumentCreateClass mtd = new MultipleDocumentCreateClass();
mtd.Mã_Hoạt_động = hoạt_động.Mã_Hoạt_động;
Dropdownlist2();
return View(mtd);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DocumentNew([Bind(Include = "Mã_Hoạt_động, Tên, Loại,Thông_tin, Nội_dung")]MultipleDocumentCreateClass mt)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
//Save into folder
file.SaveAs(Server.MapPath("/App_Data/Video/" + fileName));
mt.Nội_dung = "~/App_Data/Video/" + fileName;
mt.Tên = Path.GetFileNameWithoutExtension(file.FileName);
}
db.MultipleDocCr(mt.Mã_Hoạt_động, mt.Tên, mt.Loại, mt.Thông_tin, mt.Nội_dung);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(mt);
}
MultipleDocumentUseClass:
public class MultipleDocumentCreateClass
{
public Nullable<int> Mã_Hoạt_động { get; set; }
public string Tên { get; set; }
public string Loại { get; set; }
public string Thông_tin { get; set; }
public string Nội_dung { get; set; }
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Hoạt động: #Model.Mã_Hoạt_động</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
<dt>
Hoạt động:
#ViewBag.act.Tên
</dt>
<div class="form-group">
#Html.LabelFor(model => model.Loại, "Thể loại", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Loại, new SelectList(ViewBag.doc, "Value", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Loại, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Thông_tin, "Thông tin", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Thông_tin, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Thông_tin, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Nội_dung, "Chọn File", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nội_dung, new { htmlAttributes = new { Type = "file" } })
#Html.ValidationMessageFor(model => model.Nội_dung, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Lưu" class="btn btn-default" />
</div>
</div>
</div>
}
The error points to this line
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
but when I add value manually without uploading, it works fine.
So the answer at the #using (Html.BeginForm()) in View
Change it into this #using (Html.BeginForm("DocumentNew", "Activity", FormMethod.Post, new { enctype = "multipart/form-data" }))

Deserializing current JSON Array to perform edit operation using web api

I am using web API to edit values from collection in MongoDB.I have added code to fetch values from mongodb and have called it in another to fetch the api to perform edit functionality.
My id is getting passed to the action and still null refernce exception occur when i fix it deserialize array error occur. I tried to put deserialize the array using code found in net but it didnt work! Why does this error occur? I am new in web api and mongo db !! Please help!
Contact.cs(Model class)
public class Contact
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
mongodbcontroller(Controller)
[System.Web.Http.HttpPut]
public Contact Edit(Contact contact)
{
var contactsList = mongoDatabase.GetCollection("contact");
WriteConcernResult result;
bool hasError = false;
string errorMessage = string.Empty;
try
{
if (!string.IsNullOrEmpty(contact.Id))
{
IMongoQuery query = Query.EQ("Id", contact.Id);
IMongoUpdate update = MongoDB.Driver.Builders.Update
//.Set("Id",contact.Id)
.Set("Name", contact.Name)
.Set("Address", contact.Address)
.Set("Phone", contact.Phone)
.Set("Email", contact.Email);
result = contactsList.Update(query, update);
contactsList.Save(contact);
hasError = result.HasLastErrorMessage;
}
}
catch(Exception ex)
{
errorMessage = ex.ToString();
}
if (!hasError)
{
return contact;
}
else
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
TestController(Consuming the api)
public ActionResult Edit(string id)
{
//Contact contact = new Contact();
Contact contact = new Contact();
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
//HTTP GET
var responseTask = client.GetAsync("?id=" + id);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Contact>();
readTask.Wait();
contact = readTask.Result;
}
}
}
catch (Exception ex)
{
}
return View(contact);
}
[HttpPost]
public ActionResult Edit(Contact contact)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
//HTTP GET
var putTask = client.PutAsJsonAsync<Contact>("contact",contact);
putTask.Wait();
var result = putTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
}
catch (Exception ex)
{
}
return View(contact);
}
Edit.cshtml(View)
#model TestApi.Models.Contact
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Screenshots of my code is attched below

Resources