How to pass mutiple textbox values using checkbox from view to controller - c#

I have a edit form where I Have two textboxes and checkbox. I am trying to update book details using checkbox. I am not sure how to pass the textbox values from view to controller using checkbox in Entity Framework. I need to save save those edited textbox box values in DB. Right now my checkboxex are not passing the edit textbox values to controller.
My Edit form looks like this
Edit Form
View :
#if (Model.Count > 0)
{
<div>
#foreach (var books in Model)
{
<div class="col-md-2">
#Html.EditorFor(model => books.caption)
#Html.ValidationMessageFor(model => books.caption)
</div>
<div class="col-md-2">
#Html.EditorFor(model => books.copies)
#Html.ValidationMessageFor(model => photos.copies)
</div>
<div class="col-md-1">
<input type="checkbox" class="checkboxes" value="#books.id" name="id" />
</div>
}
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="submitButton" value="UPDATE" />
<input type="submit" name="submitButton" value="ADD"/>
<input type="submit" name="submitButton" value="DELETE" />
</div>
</div>
Contoller :
public ActionResult EditBooks(int id, IEnumerable<int> id, string submitButton,
[Bind(Include ="id,caption,copies")] Books books)
{
switch (submitButton)
{
case: UPDATE
if (ModelState.IsValid)
{
try
{
foreach (var item in id)
{
var update = _db.Books.FirstOrDefault(s => s.id == item);
if (update != null)
{
_db.MyTable.Add(update);
_db.SaveChanges();
}
return RedirectToAction("Edit", new {id});
}
}
}
}
}
I am not sure my controller code is right.

Related

Delete post method returns null

I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations
// GET-DELETE
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
Category obj = _db.Category.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
//POST-DELETE
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? id)
{
Category obj = _db.Category.Find(id);
if (id == null)
{
return NotFound();
}
_db.Category.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
and here is my View
#model RockyWebsite.Models.Category
<form method="post" asp-action="DeletePost">
#Html.HiddenFor(id => id.CategoryId)
<input asp-for="CategoryId" hidden />
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">Delete Category</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row">
<div class="col-4">
<label asp-for="CategoryName"></label>
</div>
<div class="col-8">
<input asp-for="CategoryName" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label asp-for="DisplayOrder"></label>
</div>
<div class="col-8">
<input asp-for="DisplayOrder" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4 row">
<div class="col">
<input type="submit" class="btn btn-danger w-100" value="Delete" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
</div>
</div>
</div>
</div>
<div class="col-4">
#* Keep this empty *#
</div>
</div>
</div>
</form>
Any help or suggestion would be very appreciated, thanks!
You're using #Html.HiddenFor(id => id.CategoryId) (well, you're actually using the tag-helper syntax too <input asp-for="CategoryId" hidden /> and you should just use one or the other, not both!) in the view which will create an input with name="CategoryId".
So, the easiest solution is probably to correct the view and update the parameter name in the controller action for DeletePost.
View:
<!-- remove this line: #Html.HiddenFor(id => id.CategoryId) -->
<!-- just use line below -->
<input type="hidden" asp-for="CategoryId" />
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? categoryId)
{
Category obj = _db.Category.Find(categoryId);
// check obj here, not id
if (obj == null)
{
return NotFound();
}
_db.Category.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
replace your form tag with this one
#Html.BeginForm("DeletePost", "controllerName", FormMethod.Post,
new {id="#Model.CategoryId"})
{
#Html.AntiForgeryToken()
and action
[HttpPost("{id}")]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int id)
add name tag to input, for example :
<input name="id" asp-for="CategoryId" hidden />
Alex

How to handle multiple submit button and check boxes in c# MVC Entity Framework?

I have a page where i am displaying image, id, name and address. I have added checkbox and multiple submit buttons to delete update or add new records.
But when I click on any submit buttons i am getting unhandled exception error. (for example I have selected a checkbox and clicked delete button my control is going to Mycontroller from view and to the delete switch case. It is deleting the record but again when it is coming back to view I am getting the NullReferenceException.)
View :
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
#if (Model.Count> 0) // .NullReferenceException
{
#foreach (var MyDB in Model)
{
<div class="col-md-2">
<img src="#Url.Content(photos.photo_url)" style="width:100px; height:100px;" />
</div>
Html.LabelFor(model => MyDB.ID, new
{
#class = "control-label col-md-2"
})
<div class="col-md-2">
#Html.EditorFor(model => MyDB.ID)
#Html.ValidationMessageFor(model => MyDB.ID)
</div>
#Html.LabelFor(model => MyDB.name, new
{
#class = "control-label col-md-2"
})
<div class="col-md-2">
#Html.EditorFor(model => MyDB.name)
#Html.ValidationMessageFor(model => MyDB.name)
</div>
#Html.LabelFor(model => MyDB.address, new
{
#class = "control-label col-md-2"
})
<div class="col-md-2">
#Html.EditorFor(model => MyDB.address)
#Html.ValidationMessageFor(model => MyDB.address)
</div>
<div class="col-md-1">
input type="checkbox" class="checkboxes" value="#MyDB.id" name="id" />
</div>
}
}
}
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="submitButton" value="UPDATE" />
<input type="submit" name="submitButton" value="ADD" />
<input type="submit" name="submitButton" value="DELETE" />
</div>
Controller :
public ActionResult MyController(IEnumerable<int> id, string submitButton)
{
switch (submitButton)
{
case "DELETE":
foreach (var item in id)
{
var delete = _db.MyDB.FirstOrDefault(s => s.id == item);
if (delete != null)
{
_db.MyDB.Remove(delete);
}
}
break;
case "ADD":
if (!ModelState.IsValid)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
if (id == null)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
break;
case "UPDATE" :
ViewBag.Message = "UPDATE";
break;
}
_db.SaveChanges();
ViewBag.Message = "Saved";
return View();
}
I found out what mistake I did. Inside controller i added return View(); it was returning null. so changed to return RedirectToAction("MyAction", new { id }); instead of return View();

Checkbox value always 0 after insert into database

I am building a website using Asp.Net MVC. I have successfully inserted my form data into the database. However, I got a problem with my checkbox, the value is always 0 in my database even if the checkbox is checked.
#using (Html.BeginForm())
{
<div class="modal-body">
<div class="form-group">
<label for="username" class="col-form-label">Name:</label>
<input type="text" class="form-control" **id="username" name="username" **>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<input type="checkbox" **id="user_privilage" name="user_privilage" **>
<label for="user" class="col-form-label">User</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
}
here is the code in controller:
[HttpPost]
public ActionResult UserMaintenance(User collection)
{
try
{
List<object> lst = new List<object>();
lst.Add(collection.username);
lst.Add(collection.user_privilage);
object[] allitems = lst.ToArray();
int output = db.Database.ExecuteSqlCommand("insert into DATABASE(username,user_privilage) values (#p0,#p1)", allitems);
if(output>0)
{
ViewBag.msg = "User has been added";
}
return View();
//return RedirectToAction("UserMaintenance");
}
catch {
return View();
}
}
Does anyone know what happened?
You are using pure html markup checkbox in that you need to set value to checkbox as true.
Model
View
Views at Runtime
POST Action Method
We have checked checkbox and submitted form we must get value true in user_privilage model property.
In Same way if we do for unchecking checkbox then we will get false value.

MVC5 model not recory the text value of textbox

I don't know what I'm doing bad.
Controller:
public class PictureController : Controller
{
// GET: Picture
public ActionResult Index()
{
return View();
}
public ActionResult AddGroup()
{
ModelPhotoGroup p = new ModelPhotoGroup();
return View(p);
}
[HttpPost]
public ActionResult AddGroup(ModelPhotoGroup p)
{
return View(p);
}
}
In AddGroup of HttpPost I get a p.GroupName = null but I'm writing text in the textbox
View:
#model Boda.WebUI.Models.ModelPhotoGroup
#{
ViewBag.Title = "";
}
<h2>Crear grupo de fotos</h2>
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-sm-8 col-md-offset-2">
<div class="well">
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.GroupName)
<div class="form-group">
#Html.LabelFor(x => x.GroupName)
#Html.TextBoxFor(x => x.GroupName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.GroupName)
</div>
<div class="btn-group">
<input type="submit" value="Guardar" class="btn btn-success" />
#Html.ActionLink("Cancelar y volver a la lista de Fotografias", "Index", null, new
{
#class = "btn btn-default"
})
</div>
}
</div>
</div>
</div>
This is the view. Only I have one TextBoxt to write the name of group
HTML Generated:
<form action="/Picture/AddGroup" method="post"><input id="GroupName" name="GroupName" type="hidden" value=""> <div class="form-group">
<label for="GroupName">GroupName</label>
<input class="form-control" id="GroupName" name="GroupName" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="GroupName" data-valmsg-replace="true"></span>
</div>
<div class="btn-group">
<input type="submit" value="Guardar" class="btn btn-success">
<a class="btn btn-default" href="/Picture">Cancelar y volver a la lista de Fotografias</a>
</div>
You have included
#Html.HiddenFor(x => x.GroupName)
before
#Html.TextBoxFor(x => x.GroupName)
The value of the hidden input will be whatever the default value of GroupName was when you initialized the model (i.e. null)
When you POST, the DefaultModelBinder sets the value of property GroupName to the first value it reads from the form data (that of the hidden input) and ignores any subsequent values with the same name, so the property is always null.
Remove the hidden input and your model will be correctly bound with the value in the textbox.
It's because you did not specify the action and controller,
add the name of action and controller in your form
#using(Html.BeginForm("AddGroup","Picture"))

viewmodel returns null on postback mvc 5

I have this problem with a viewmodel, when the view is posted I'm getting null values for all the properties.
I've researched a bit, I can see multiple ppl have this problem, I tried some of the solutions but none of them works for me.
This is what I have:
Viewmodel:
public class EventViewModel
{
public projectEvent ProjectEvent { get; set; }
public List<eventType> eventTypes { get; set; }
}
Controller:
[HttpGet]
public ActionResult AddEditEvent(int? id)
{
var eventViewModel = new EventViewModel();
var projectEventModel = new projectEvent();
if (id != null)
{
using (var db = new DBEntities())
{
projectEventModel = (from p in db.projectEvents
where p.eventID == id
select p).FirstOrDefault();
}
}
eventViewModel.ProjectEvent = projectEventModel;
using (var db = new DBEntities())
{
eventViewModel.eventTypes = (from p in db.eventTypes
select p).ToList();
}
return View(eventViewModel);
}
[HttpPost]
public ActionResult AddEditEvent(EventViewModel projectEvent)
{
if (ModelState.IsValid)
{
using (var db = new DBEntities())
{
db.projectEvents.AddOrUpdate(projectEvent);
db.SaveChanges();
}
}
return RedirectToAction("Events");
}
View:
#model TTB.ViewModels.EventViewModel
#{
Layout = "~/Views/Shared/_Layout_Main.cshtml";
}
<h2>Add/Edit Event</h2>
#using (Html.BeginForm("AddEditEvent", "Admin"))
{
<div class="container">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
#Html.TextBoxFor(m => m.ProjectEvent.eventName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProjectEvent.eventName)
</div>
<div class="form-group">
<label for="name">Date</label>
#Html.TextBoxFor(m => m.ProjectEvent.eventDate, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProjectEvent.eventDate)
</div>
<div class="form-group">
<label for="name">Event Type</label>
#Html.DropDownListFor(v => v.ProjectEvent.eventType, new SelectList(Model.eventTypes, "eventTypeID", "eventTypeName"), new { #class = "form-control dropdown" })
</div>
#Html.HiddenFor(m => m.ProjectEvent.eventID)
</div>
<div class="col-md-8">
<input type="submit" class="btn btn-success btn-lg btnSaveEdit" value="Save" />
</div>
</div>
}
What am I doing wrong?
Update
Rendered html output:
<form action="/Admin/AddEditEvent" method="post"> <div class="container">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" data-val="true" data-val-required="The eventName field is required." id="ProjectEvent_eventName" name="ProjectEvent.eventName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="ProjectEvent.eventName" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="name">Date</label>
<input class="form-control" data-val="true" data-val-date="The field eventDate must be a date." data-val-required="The eventDate field is required." id="ProjectEvent_eventDate" name="ProjectEvent.eventDate" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="ProjectEvent.eventDate" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="name">Event Type</label>
<select class="form-control dropdown" id="ProjectEvent_eventType" name="ProjectEvent.eventType"><option value="1">movie</option>
</select>
</div>
<input data-val="true" data-val-number="The field eventID must be a number." data-val-required="The eventID field is required." id="ProjectEvent_eventID" name="ProjectEvent.eventID" type="hidden" value="0" />
</div>
<div class="col-md-8">
<input type="submit" class="btn btn-success btn-lg btnSaveEdit" value="Save" />
</div>
</div>
</form>
It is because you have a property on your model called projectEvent and you refer to your model as projectEvent when it is passed back into the controller.
Change
public ActionResult AddEditEvent(EventViewModel projectEvent)
To
public ActionResult AddEditEvent(EventViewModel model)
(or another name of your choosing)
http://tech.pro/blog/1930/don-t-name-a-model-the-same-as-a-property-you-re-trying-bind-in-aspnet-mvc

Categories