How do I update a specific database entry with a view model as controller method attribute - asp.net-mvc

I have an input table in my website which is connected to a View Model. In the controller method, I pass this View Model to the controller and vice versa, meaning the controller populates the view model with data from the data base and the view returns a view model populated with form data the user might have entered.
The problem is that once the view received the view model object, the "ID" attribute from the database is no longer there. When the Post method is called, there is no way to know which database entry must be updated.
My question is: How do I update a specific database entry when I pass a view model to the controller method?
Example Controller Method:
[HttpPost]
public ActionResult method(ViewModel vm)
{
DataContext.Context.Where(x => x.ID == vm.Object.ID) // this is where vm.Object.ID always returns "0", not the actual ID from the database entry
Context.SaveChanges();
return View(vm);
}
If you need more information, please let me know. Also, using jquery is not a viable option for this project. Thanks a lot for your help!
Edit:
View:
#model MyANTon.ViewModels.Q4_Answer_VM
#{
ViewBag.Title = "myANTon Anforderungserfassung";
ViewBag.HideNavBar = false;
}
#using (Html.BeginForm())
{
<div class="container">
<div class="jumbotron">
<hr />
<table class="grid" id="datatable">
<tr>
<th>Nr.</th>
<th>Last</th>
<th>Quelle</th>
<th>Ziel</th>
<th>Frequenz [/h]</th>
<th>Abstand [m]</th>
<th></th>
<th></th>
#{int i = 1; }
#for (var a = 0; a < Model.Matrix.Count; a++)
{
<tr>
<td>#(i++)</td>
<td>#Html.TextBoxFor(x => Model.Matrix[a].Load)</td>
<td>#Html.TextAreaFor(x => Model.Matrix[a].Source)</td>
<td>#Html.TextAreaFor(x => Model.Matrix[a].Goal)</td>
<td>#Html.TextAreaFor(x => Model.Matrix[a].Frequency)</td>
<td>#Html.TextAreaFor(x => Model.Matrix[a].Distance)</td>
<td><input type="submit" name="+" class="btn btn-default" value="+" /></td>
<td><input type="submit" class="btn btn-default" value="-" /></td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" name="Speichern" value="Speichern" />
<input type="submit" class="btn btn-default" value="Speichern und weiter" />
<input type="button" class="btn btn-default" value="Weiter zu Schritt 5" onclick="#("window.location.href='" + #Url.Action("Q_Fifthpage", "Home") + "'");" />
</div>
</div>
</div>
</div>
}
GET Method:
[HttpGet]
public ActionResult Q_FourthPage()
{
// get current Questionnaire ID
int CurrentQstID = Convert.ToInt32(Session["qstid"]);
// create vm object. Capacity is a column in the table.
var Q4ViewModel = new ViewModels.Q4_Answer_VM();
// look for existing input data columns for this questionnaire in db
if (db.Capacities.Any(x => x.Questionnaire_ID == CurrentQstID))
{
// answers exist
Q4ViewModel.Matrix.AddRange(db.Capacities.Where(x => x.Questionnaire_ID == CurrentQstID));
}
else
{
// new capacity matrix
Q4ViewModel.TMatrix = db.QuestionTexts.Where(x => x.ID == 21).FirstOrDefault();
Q4ViewModel.Matrix = new List<Models.Capacity>();
}
var tmpcapacity = new Models.Capacity();
tmpcapacity.Questionnaire_ID = Convert.ToInt32(Session["qstid"]);
Q4ViewModel.Matrix.Add(tmpcapacity);
db.Capacities.Add(tmpcapacity);
db.SaveChanges();
return View(Q4ViewModel);
}
POST Method:
[HttpPost]
public ActionResult Q_FourthPage(ViewModels.Q4_Answer_VM vm)
{
int currentQst = Convert.ToInt32(Session["qstid"]);
if (Request.Form["+"] != null)
{
var tmpcapacity = new Models.Capacity();
tmpcapacity.Questionnaire_ID = currentQst;
vm.Matrix.Add(tmpcapacity);
db.Capacities.Add(tmpcapacity);
db.SaveChanges();
return View(vm);
}
if (Request.Form["Speichern"] != null)
{
// save data
if (!ModelState.IsValid) return View("~/Views/Shared/Error.cshtml");
var tmpcapacity = new Models.Capacity();
for (var a = 0; a < vm.Matrix.Count; a++)
{
var current = vm.Matrix[a];
current.ID = vm.Matrix[a].ID;
if (db.Capacities.Any(x => x.ID == current.ID))
// if clause never triggers true
// vm does not contain capacity ID
{
// column exists and is changed (or not)
tmpcapacity.Distance = vm.Matrix[a].Distance;
tmpcapacity.Frequency = vm.Matrix[a].Frequency;
tmpcapacity.Source = vm.Matrix[a].Source;
tmpcapacity.Goal = vm.Matrix[a].Goal;
tmpcapacity.Load = vm.Matrix[a].Load;
Models.Capacity c = db.Capacities.Where(x => x.ID == current.ID).FirstOrDefault();
c = tmpcapacity;
db.SaveChanges();
}
else
{
// new column
tmpcapacity.Distance = vm.Matrix[a].Distance;
tmpcapacity.Frequency = vm.Matrix[a].Frequency;
tmpcapacity.Source = vm.Matrix[a].Source;
tmpcapacity.Goal = vm.Matrix[a].Goal;
tmpcapacity.Load = vm.Matrix[a].Load;
tmpcapacity.Questionnaire_ID = currentQst;
db.Capacities.Add(tmpcapacity);
db.SaveChanges();
}
}
db.SaveChanges();
}
return View(vm);
}

If you need to bind the ID to the Model then you need to use hidden filed under the form when you are using Razor.
#Html.HiddenFor(model => model.Id)
For more details
#using (Html.BeginForm("method", "ControllerName", FormMethod.Post))
{
#Html.HiddenFor(Model=>Model.ID)
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Button" />
</div>
</div>
}
Now you can access ID at your controller action method.

If you want to "save" the object ID and get it back when the post occurs, you need to store it into a hidden field using the .HiddenFor() HTML helper - something like this:
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.Object.Id);
<div class="container">
<div class="jumbotron">
Then, upon your POST, you should get back the Object.ID in your post body and you should be able to tell which object this is for.

Related

How can i pass multiple radio button values to controller in ASP.NET MVC?

I've a model that contains 3 tables in my view.
public class InExam
{
public AutoTests TheTest { get; set; }
public List<InTest> TheQuestions { get; set; }
public IEnumerable<Result> SingleQuee { get; set; }
}
First one made to get the detailed page, like "admin/AutoTests/id"
Second one made to get a list of questions linked to the page
Third one is to save radio button strings to post it back into the controller
my plan is to get (say) 20 questions that are linked with the detailed page, Adding 4 radio buttons for each question, and post back every selected button to the controller.
my view form :
#using (Html.BeginForm("Test", "Exams", new { id = Model.TheTest.id }, FormMethod.Post))
{
foreach (var item in Model.TheQuestions)
{
Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();
<div class="container" style="padding-top:50px;direction:rtl;">
<h4 style="text-align:right;font-weight:bold;">#item.Question</h4>
<div class="container">
<div class="row" style="direction:rtl;">
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "1" })
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "2" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer2</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "3" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer3</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "4" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer4</h5>
</div>
</div>
#Html.HiddenFor(m => singleQuee.Question)
</div>
</div>
</div>
}
<button class="btn botton" type="submit" onclick="return confirm('');">END</button>
}
i used this line "Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();" in my view because i can't use tuple foreach ( C# ver. 5 )
This is my controller code :
[HttpGet]public ActionResult Test(int? id)
{
using (KafoEntities db = new KafoEntities())
{
InExam model = new InExam();
model.TheTest = db.AutoTests.Where(x => x.id == id).FirstOrDefault();
model.TheQuestions = db.InTest.Where(x => x.UserEmail == currentUser.Email && x.ExamId == model.TheTest.id).OrderByDescending(x => x.id).Take(Convert.ToInt32(model.TheTest.QuestionsNumber)).ToList();
model.SingleQuee = db.Result.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Test(int? id, List<Result> singleQuee)
{
using (KafoEntities db = new KafoEntities())
{
int result = 0;
foreach (Result item in singleQuee)
{
Result sets = db.Result.Where(x => x.id == item.id).FirstOrDefault();
sets.Question = item.Question;
db.SaveChanges();
var check = db.InTest.Where(x => x.Question == item.Question).FirstOrDefault();
if (check != null)
{
if (item.Question == "1")
{
result++;
}
}
}
return RedirectToAction("Results", "Exams", new { Controller = "Exams", Action = "Results", id = done.id });
}
}
I first save the new string that came from the radio button value into the result record, then i call it back in the if condition to check it's value
The problem here is i get a
Object reference not set to an instance of an object.
when i post the test, it means that the list is empty, so i need to know what makes the radio buttons not working,
Thanks.
If you want to bind a List of object in Mvc, you should name the controller like "ModelName[indx].PropertyName". In your case it should be "singleQuee[0].Question".
Code Sample
var Indx = 0;
foreach (var item in Model.TheQuestions)
{
.....
var radioName = $"singleQuee[{Indx}].Question";
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
<input type="radio" name="#radioName" value="1" />
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
.....
}
Action Method

Multiple forms in one view page

I'm working on an application that handles employee's profile.
I have 3 forms (all in the same controller) in a single view page, but it only saves the 1st form. And when i save the 2nd form, it clears the values of the 1st and 3rd form.
Here is my code:
Views/EMPs/Index:
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="personalsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="jobsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="otherssubmit" class="btn btn-success" />
</div>
</div>
}
EMPsController
public ActionResult Edit([Bind(Include = "lineno,EMPNO,IDNO..")] EMP eMP)
{
if (ModelState.IsValid)
{
if (Request.Form["personalsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["jobsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["otherssubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.PathAndQuery);
}
return View(eMP);
}
I couldn't put them all in one form, because i used an ajax beginForm between them for another crud method. Since I've read that nested forms are not recommended.
Is there a way to save one form without it clearing the values of the other forms?
Is there a way to save one form without it clearing the values of the other forms?
You could simply use ajax.beginform for each of those forms;
How to use Simple Ajax Beginform in Asp.net MVC 4?
Or you could make your own ajax implementation
https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc
Or you could just go ahead and bind everything on your model;
// don't need to specify which properties to bind, all of the available properties in your view will be bound to the model on POST
public ActionResult Edit(EMP eMP)
{
if(eMP.FirstName!=null ...){
// ... do some checking depending on what values are submitted
}
// save profile here
// when you return the view
return View(eMP);
}
but for this method you need to only have 1 form for Personal,Job, and Others.
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!--put all your employee input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your job input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your others input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
}

ASP.NET MVC - Check Box List for Link Table Values

Hoping someone can help me out, what I am trying to achieve a checkbox list (populated from a database table) which then inserts into a link table.
I'm not sure how best to achieve this, this is what I have so far which displays correctly, but I'm not sure how I can get this to save.
#using (Html.BeginForm("Create", "ReviewChecklistsController"))
{
foreach (var item in ViewBag.ChecklistId)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="#item.Value"
value="#item.Value" /> #item.Text
</label>
</div>
}
<p></p>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save Checklist" />
</div>
}
Below is how I have set it up in the database, if you need any more information please let me know. I am using Entity Framework.
What I want is ReviewChecklist\ChecklistId to map to List_Checklist\ChecklistId and then State is just a boolean so if the checkbox is checked or not.
I've managed to get it working using the below. Is this okay, or is there a better way to do it?
#using (Html.BeginForm("Create", "ReviewChecklistsController"))
{
int i = 0;
foreach (var item in ViewBag.ChecklistId)
{
var nameStatus = "reviewChecklist[" + i + "].Status";
var nameReviewId = "reviewChecklist[" + i + "].ReviewId";
var nameChecklistId = "reviewChecklist[" + i + "].ChecklistId";
#Html.HiddenFor(model => model.ReviewId, new { Name = nameReviewId })
#Html.HiddenFor(model => model.ChecklistId, new { Name = nameChecklistId, Value = item.Value })
<p>
#Html.CheckBoxFor(model => model.Status, new { Name = nameStatus })
#item.Text
</p>
i++;
}
<p></p>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save Checklist" />
</div>
}

Additional validation message displayed on mvc app

I have a simple mvc web app, that is searching transactions in the DB using a specified search parameter(named RA number), now I decided to add jquery block ui on my app and I then realized the block fires even when an empty string("" single or double space bar in textbox) is entered.
I have data annotation in my RA view model, I then added an AllowEmptryStrings = false attribute on my view model property, see code below
public class SearchByRAViewModel
{
[Required(ErrorMessage = "Please enter an RA number",AllowEmptyStrings = false)]
public string RANumber { get; set; }
}
Here is my action method from my controller code
public ActionResult SearchTollTransactions(SearchByRAViewModel raViewModel)
{
List<TollScrapingTransactionScreen> tollScrapingList = new List<TollScrapingTransactionScreen>();
if (ModelState.IsValid)
{
tollScrapingList = GetTransactionByRA(raViewModel.RANumber);
ViewBag.RANumber = raViewModel.RANumber;
return View(tollScrapingList);
}
else
{
return View("Index");
}
}
My only problem now is, there seems to be an extra validation message displayed on the search page(index) if there is an empty string in the search text box, see screenshot
Here is my block ui section, in case someone wonders where it is
$('#btnSearch').click(function () {
// there should be at least a value for ra before firing the blockui
var raValue = $('#raNumber').val();
if (!raValue || raValue.trim() === '') {
return;
}
else {
$.blockUI();
}
});
This is the part of my view, which is inside the normal #using(Html.BegingForm)
<div class="form-horizontal">
<div class="form-group">
<div class="panel panel-default">
<div class="panel-heading">Search by RA number</div>
<div class="panel-body">
<div class="col-sm-12">
<table class="table form-table">
<tr>
<th class="col-sm-2">#Html.DisplayNameFor(model => model.RANumber)</th>
<td class="col-sm-10">
#Html.TextBoxFor(model => model.RANumber, new { #class = "form-control", #tabindex = 1, #id = "raNumber" })
#Html.ValidationMessageFor(model => model.RANumber)
</td>
</tr>
</table>
</div>
<div class="btn-toolbar col-sm-12">
<input type="submit" value="Search Transaction" class="btn pull-right" tabindex="2" id="btnSearch" />
</div>
</div>
</div>
</div>
</div>

Partial View with self updating

I'm learning ASP.NET MVC and I've encountered a problem in my practice project (MVC Music Store). I have made a partial view to search for an artist. I expect the partial view to take no arguments and work on its own.
Partial view in the right half part
I have a view specific model for the Artist Search Partial View. The model is as follows:
public class ArtistSearch
{
public string SearchString { get; set; }
public List<Artist> SearchResult { get; set; }
public ArtistSearch()
{
SearchResult=new List<Artist>();
}
}
Controller code is as follows:
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView(asResult);
}
The Partial View is as follows:
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-box">
<form action="#Url.Action("Search","Artist")" method="post" role="form">
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
</form>
</div>
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id" >
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>
I wish to place this partial view anywhere on the site. Lets say i placed it(using RenderAction) on Artist/Index Controllers View page.
The simple functionality that I'm trying to achieve is that when i click on search it should self update the partial view with search results. Right now it is transferring me to Artist/Search page.
Thanks for the patience.
Try to use Ajax.BeginForm, below is an example:
Action
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView("MyParitalView",asResult);
}
View
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions { UpdateTargetId = "result" }))
{
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
}
<div id="result"></div>
Parital View : MyParitalView
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id">
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>

Resources