Not able to render partial view as a part of view - c#

There are a couple of questions I referred on rendering partial views in mvc4. But my problem is that I have a division(DisplayRecords) in my view and want the partial view to open in that division instead of a different view on click of 'view' button.
But that is not happening because in the controller I am returning the partial view because if I return the view, I cannot pass the list containing data.
On returning view, it throws an error that the view cannot accept that type of parameter and the partial view will not work without the list being passed.
I tried assigning the list to a model property and pass that property value to partial view from client side but that throws a null reference exception.
Can someone suggest how I can fix this.
Here is what I have written:
My view:
#model mvcEmail.Models.EmailModel
#*<script type="text/javascript">
var command = document.getElementById("FirstName");
alert(command);
if (command == "Value")
$('#DisplayRecords').load('/Email/Index2');
</script>*#
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (#Html.BeginForm())
{
<div>
#* #Html.Label(Model.Acknowledge, new { id = "Acknowledge" })
<br />*#
#Html.TextBoxFor(model => model.FirstName, new { id = "FirstName", #class = "ClassName" })
<br />
#Html.TextBoxFor(model => model.PhoneNumber, new { id = "PhoneNumber", #class = "ClassPhoneNumber" })
<br />
<input type="submit" name="Command" value="Submit" />
<input type="submit" name="Command" value="View" />
</div>
<div id="DisplayRecords">
#if (ViewBag.query == "View")
{
#Html.Partial("Index2")
}
</div>
}
My partial view:
#model IEnumerable<mvcEmail.Models.EmailModel>
<p>
#Html.ActionLink("Create New", "Index")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
#* <td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>*#
</tr>
}
</table>
My controller where I am passing list to view:
if (Command == "View")
{
ViewBag.query = "View";
//var records = new DisplayRecords();
List<EmailModel> recs = new List<EmailModel>();
cmd.CommandText = "DisplayRecords";
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
model = new EmailModel();
model.PhoneNumber = reader["phone"].ToString();
model.FirstName = reader["Name"].ToString();
recs.Add(model);
}
con.Close();
con.Dispose();
return PartialView("Index2", recs);
//return View(recs);
}

Your Partial view is not getting its instance of model.You need to provide your model during calling partial view in view as -
#Html.Partial("Index2", new List<mvcEmail.Models.EmailModel>(){this.Model})
or I will recommend to write another controller action which will return your partial view with model as -
public ActionResult PartialView()
{
List<mvcEmail.Models.EmailModel> emailListModel = new List<mvcEmail.Models.EmailModel>();
return PartialView(emailListModel);
}
and then call it using -
#{Html.RenderAction("PartialView", "Controller_name",null);}
This will make your code better as with single responsibility principle.
I hope this will help you.

Related

why Html.checkboxfor is not sends or changes the boolean value of the model?

I have a simple project that allows the customer to select multiple users and remove them from the DataBase. But the check boxes are not change or sent the isSelected variable which is tells the server that which users are have to be removed.
Client Side:
#model IEnumerable<WebApplication1.Models.User>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
int i;
}
<h2><strong>جدول</strong></h2>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("اضافه کردن کاربر", "Create"
, null, new { #class = "btn btn-success", #id = "btnCreate" })
<input type="submit" class="btn btn-danger hidden" id="btnMultipleDelete" value="حذف کاربران" />
</p>
<table class="table" border="0" style="user-select: none;">
<tr>
<th>
<strong>نام</strong>
</th>
<th>
<strong>نام خانوادگی</strong>
</th>
<th>
<strong>سنّ</strong>
</th>
<th></th>
</tr>
#for(i = 0; i < Model.Count(); i++)
{
<tr class="mainList" id="tr-#i"
onmouseover="changeCurrentRow(this.id), mouseIn(true)"
onmouseout="clearCurrentRow(), mouseIn(false)">
<td class="IndexInfo">
<span class="IndexText">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_FirstName)
</span>
</td>
<td class="IndexInfo">
<span class="IndexText">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_LastName)
</span>
</td>
<td class="IndexInfo">
<span class="IndexText persianNumber">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_Age)
</span>
</td>
<td align="center" style="flex:3">
#Html.ActionLink("ویرایش", "Edit", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-primary", #id = "btnEdit-" + i })
#Html.ActionLink("مشاهده", "Details", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-secondary", #id = "btnDetail-" + i })
#Html.ActionLink("حذف", "Delete", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-warning", #id = "btnDelete-" + i })
#Html.HiddenFor(u => u.ToList()[i].User_Id)
#Html.HiddenFor(u => u.ToList()[i].User_FirstName)
#Html.HiddenFor(u => u.ToList()[i].User_LastName)
#Html.HiddenFor(u => u.ToList()[i].User_Age)
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { #class = "", #id = "cb-" + i })
</td>
</tr>
}
</table>
}
Server Side:
[HttpPost]
public ActionResult Index(IEnumerable<User> users)
{
if (users.Count() == 0)
{
return RedirectToAction("Index");
}
else
{
User user;
foreach (User u in users)
{
if (u.IsSelected)
{
user = db.Users.ToList().Find(x => x.User_Id == u.User_Id);
db.Users.Remove(user);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
}
notice that i have tried to put a hidden input for isSelected Variable But that still doesn't work
so, while no one cares about my question i found the solution by my self.
Controller can not receive the IsSelected property from the View because i have changed the identity of the checkbox like id,name and ...
that means if i dont change the the identities of the checkbox, the code will works but even this solution leads us to another problem that you no longer can find the checkbox by JS. so i dont give this answer green tick until someone finds a better way to fix it.
for this solution something that you have to do is change the check box code from this:
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { #class = "", #id = "cb-" + i })
to this:
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected})
and it basically will works.

Why are the parameters of my action null?

I'm trying to make a page using ASP MVC 5 with C# in which I have some controls to type search parameters and a table where the results are shown.
The thing is that the user should be allowed to edit the text of two fields in the table and save the changes.
To accomplish this, my view receives a model with two objects as properties, one for the search parameters and one for the result list, like this:
public class SEARCH_PAGE
{
public List<VIEW_DATA_APR> table{ get; set; }
public SEARCH parameters{ get; set; }
}
Then my Controller is this:
public class CargaAPRController : Controller
{
private datasource db = new datasource();
// GET: CargaAPR
public ActionResult Index()
{
try
{
List<SelectListItem> items = new SelectList(db.COMPANY, "IDCOMPANY", "COMPANYNAME").ToList();
items.Insert(0, (new SelectListItem { Text = "ALL", Value = "0" }));
ViewData["IDCOMPANY"] = items;
var letters = (from c in db.LETTERS
select new VIEW_DATA_APR
{
company = c.COMPANY.COMPANYNAME,
idLetter = c.IDLETTER,
nic = "not found",
client = "not found",
energy = 0,
money = 0,
period = "",
letterCode = c.LETTERCODE
});
SEARCH_PAGE sp = new SEARCH_PAGE();
sp.table= letters.ToList();
sp.parameters= new SEARCH();
return View(sp);
}
catch (Exception ex)
{
return RedirectToAction("Error", new RouteValueDictionary(new { controller = "Users", action = "Error", mensaje = "Error: " + ex.Message }));
}
}
[HttpPost]
public ActionResult Index(SEARCH_PAGE model)
{
try
{
List<SelectListItem> items = new SelectList(db.COMPANY, "IDCOMPANY", "COMPANYNAME").ToList();
items.Insert(0, (new SelectListItem { Text = "ALL", Value = "0" }));
ViewData["IDCOMPANY"] = items;
decimal company = Decimal.Parse(model.parameters.company);
var letters= (from c in db.LETTERS
where (company== 0 ? c.IDCOMPANY: company) == c.IDCOMPANY
select new VIEW_DATA_APR
{
company= c.COMPANY.COMPANYNAME,
idLetter= c.IDLETTER,
nic = "not found",
client = "not found",
energy = 0,
money = 0,
period = "",
letterCode = c.LETTERCODE
});
SEARCH_PAGE sp = new SEARCH_PAGE();
sp.table= letters.ToList();
sp.parameters = model.parameters;
return View(sp);
}
catch (Exception ex)
{
return RedirectToAction("Error", new RouteValueDictionary(new { controller = "Users", action = "Error", mensaje = "Error: " + ex.Message }));
}
}
[HttpPost]
public ActionResult Save(SEARCH_PAGE model_search_page )
{
return View();
}
}
And my View is:
#using datasource.Models
#model SEARCH_PAGE
#{
ViewBag.Title = "Load APR";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Styles.Render("~/Content/energetica.css")
<meta name="viewport" content="width=device-width" />
<title>Letters</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<div class="container-fluid">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<div class="row">
<div class="col-md-1">
<a href="#Url.Action("Index", "LoadFiles")" class="elements">
<img class="img img-responsive" style="width:25px; height:26px;padding:1px" src="~/img/BackIcon.png">
</a>
</div>
<div class="col-md-11 text-left" style="padding:1px;">
LOAD APR
</div>
</div>
</div>
</div>
#using (Html.BeginForm("Index","LoadAPR", FormMethod.Post, null))
{
<table style="width:100%">
<tr>
<td style="width:10%">
<b>COMPANY: </b>
</td>
<td style="width:20%">
#Html.DropDownListFor(m => m.parameters.company, (IEnumerable<SelectListItem>)ViewData["IDCOMPANY"], new { htmlAttributes = new { #class = "form-control" } })
</td>
<td style="width:10%">
<b>PERIOD: </b>
</td>
<td style="width:20%">
#Html.EditorFor(m => m.parameters.period)
</td>
<td style="width:20%; text-align:right">
<input type="submit" name="SEARCH" value="SEARCH" />
</td>
</tr>
<tr>
<td style="width:10%">
<b>CLIENT: </b>
</td>
<td style="width:20%">
#Html.EditorFor(m => m.parameters.client)
</td>
<td style="width:10%">
<b>NIC: </b>
</td>
<td style="width:20%">
#Html.EditorFor(m => m.parameters.nic)
</td>
</tr>
</table>
}
<br />
#using (Html.BeginForm("Save", "LoadAPR", FormMethod.Post, null))
{
<div style="overflow-y: scroll; max-height: 300px">
<table style="width:100%">
<tr>
<th>
#Html.Label("LBDIS", "Company")
</th>
<th>
#Html.Label("LBNLETTER", "Letter Code")
</th>
<th>
#Html.Label("LBNIC", "NIC")
</th>
<th>
#Html.Label("LBCLIENT", "Client")
</th>
<th>
#Html.Label("LBENERGY", "Energy")
</th>
<th>
#Html.Label("LBMONEY", "Money")
</th>
</tr>
#foreach (var item in Model.table)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.company)
</td>
<td>
#Html.DisplayFor(modelItem => item.letterCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.nic)
</td>
<td>
#Html.DisplayFor(modelItem => item.client)
</td>
<td>
#Html.EditorFor(modelItem => item.energy)
</td>
<td>
#Html.EditorFor(modelItem => item.money)
</td>
</tr>
}
</table>
</div>
<br />
<div style="width:100%; text-align:right;">
<input class="btn-addUser" type="submit" value="Save" />
</div>
}
</div>
So when I run it and click on my first button, the POST Index parameter receives just the parameters part of the object, the table part is null
And when I click on my second button, the POST Save parameter comes null in both properties.
I have tried so many different ways of seding the Model as parameter but nothing is working. Could you tell me what's wrong? Am I using he BeginForm in the correct way?
Thank you in advance.

MVC viewmodel is null on post (editing multiple rows)

I'm new to ASP.NET MVC and have been searching for a solution to this problem for hours. I'm trying to create a site where admins can go in and approve registration user requests and also assign them to a user group. I'm getting data from multiple tables so I created a viewmodel.
I finally have the GET Edit controller working to display the data, but can't figure out how the POST Edit should work. When I was debugging, I realized that the viewmodel I was trying to return had only null values.
I'm not sure if there are many things wrong with this code or just one. On postback, I need to update some values in the Access table. If you need more information from me, just let me know. Thanks!
ViewModel:
using System.Collections.Generic;
using AccessRequests.Models;
using System.ComponentModel.DataAnnotations;
namespace AccessRequests.ViewModels
{
public class UserAccessData
{
public IEnumerable<User> Users { get; set; }
public IEnumerable<Access> Accesses { get; set; }
public IEnumerable<UserGroup> UserGroups { get; set; }
}
}
Controller:
// GET: Accesses/Edit/5
public ActionResult Edit(string brand, string group)
{
var viewModel = new UserAccessData();
viewModel.Users = db.Users
.Include(i => i.Accesses)
.OrderBy(i => i.UserName);
viewModel.UserGroups = db.UserGroups
.Where(i => i.Groups.Contains(group));
if (brand != null)
{
viewModel.Accesses = db.Accesses
.Include(x => x.User)
.Where(x => x.Brand.ToUpper() == brand);
}
return View(viewModel);
}
// POST: Accesses/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Access access, UserAccessData editaccess)
{
//code here
}
View:
#model AccessRequests.ViewModels.UserAccessData
#{
ViewBag.Title = "Edit";
}
<h2>Edit Access</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<table class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Company</th>
<th>Role</th>
<th>Region</th>
<th>User Group</th>
<th>Approve</th>
<th>Deny Reason</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Accesses)
{
#Html.HiddenFor(modelItem => item.UserName)
<tr>
<td>
#Html.DisplayFor(modelItem => item.User.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Company)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Role)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Region)
</td>
<td>
#Html.DropDownListFor(m => m.UserGroups, new SelectList(Model.UserGroups, "Groups", "GroupDescription"), "Please select a User Group")
</td>
<td>
#Html.DropDownListFor(modelItem => item.Approved, new SelectList(
new List<Object>{
new { value = 0 , text = "" },
new { value = "YES" , text = "YES" },
new { value = "NO" , text = "NO"}
},"value","text", 2))
</td>
<td>
#Html.EditorFor(modelItem => item.DenyReason, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(modelItem => item.DenyReason, "", new { #class = "text-danger" })
</td>
</tr>
}
</tbody>
</table>
<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>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
In order to post to a collection property, your field names need to be in the form of something like: Accesses[0].Approved, Accesses[1].Approved, etc. In order to achieve that, you need to use a for loop rather than foreach. You'll also need to change your property's type from IEnumerable<Access> to List<Access>.
#for (var i = 0; i < Model.Accesses.Count(); i++)
{
...
#Html.DropDownListFor(m => Model.Accesses[i].Approved, ...)
}
Also, bear in mind that only those properties which have actual HTML fields that participate in the the post will have values in your post action. Everything else will either be null or whatever default value the property may have. If you save an entity with properties that have been nulled out because they weren't posted, you will overwrite those properties in your database. You need to take care to either make sure all the necessary data comes through in the post or that you repopulate said data from the the database before attempting to save anything.

Refresh partial view content when submit button clicked

I have a strongly typed view, which has a form in which I put one field showtime when the submit button is clicked I want to save the entry into database also display that entry along with other entries on the database inside the partial view I put on the main view . When the Index action method is called the Main view is rendered .I want to update the Partial view when a new entry is saved without reloading the whole page ,just refresh the partial page.
Here is my view :
#model Bookmany.Admin.Models.Theater.TheaterShowTimeViewModel
#{
ViewBag.Title = "Theater showTimes / BookMany";
}
<h3>Theater ShowTimes</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.TheaterID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TheaterID, Model.AvailableTheaters)
#Html.ValidationMessageFor(model => model.TheaterID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ShowTimeName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ShowTimeName)
#Html.ValidationMessageFor(model => model.ShowTimeName)
</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.Partial("_TheaterShowTimeList", Model.TheaterShowTimeList)
</div>
Here is my partial view :
#model IEnumerable<Bookmany.Core.Domain.TheaterShowTime>
<table class="table">
<tr>
<th>
Theater Name
</th>
<th>
#Html.DisplayNameFor(model => model.ShowTimeName)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Theater.TheaterName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.TheaterShowTimeID }) |
#Html.ActionLink("Details", "Details", new { id = item.TheaterShowTimeID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.TheaterShowTimeID })
</td>
</tr>
}
My action method :
public ActionResult Index()
{
var model = new TheaterShowTimeViewModel();
//Bind Theater dropdown with selected value
model.AvailableTheaters = GetTheaters();
model.TheaterShowTimeList = _theaterShowTimeService.GetAllTheaterShowTime();
return View(model);
}
[HttpPost]
public ActionResult Index(TheaterShowTimeViewModel model)
{
if (ModelState.IsValid)
{
InsertOrUpdateTheaterShowTime(model);
model.TheaterShowTimeList=_theaterShowTimeService.GetAllTheaterShowTime();
return PartialView("_TheaterShowTimeList", model.TheaterShowTimeList);
}
return View(model);
}
my problems :
when I enter one value in the field and submit the form ,the entry saved now the partial view is only returned with the updated list
I want to update the partial view without reloading the whole page how do achieve that?
Like Stephen Muecke said I posted the form using ajax when the submit button clicked
<script type="text/javascript" >
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#ShowTimeName').val("");
$('#theaterShowList').html(result);
}
});
}
return false;
});
});
</script>
In my action method which returns the partial view :
[HttpPost]
public ActionResult Index(TheaterShowTimeViewModel model)
{
if (ModelState.IsValid)
{
InsertOrUpdateTheaterShowTime(model);
model.TheaterShowTimeList=_theaterShowTimeService.GetAllTheaterShowTime();
//return RedirectToAction("Index", new { id = model.TheaterID });
//return Json(model.TheaterShowTimeList);
return PartialView("_TheaterShowTimeList", model.TheaterShowTimeList);
}
return View(model);
}
this resolved my issue

Using one view for index and create in mvc4

I am trying to use one view in which I display current results which has the ability to add a new record. I looked at this post and also this post and pieced together something I think should work but it will not save to the database. Here is my view model:
public class LabIndexViewModel
{
public Lab Lab { get; set; }
public IEnumerable<Lab> Labs { get; set; }
}
And in my controller I have this in my index:
public ActionResult Index(int patid = 0, Lab lab = null)
{
ViewBag.Finalize = PatientSubmitted(patid);
ViewBag.DispPatientId = patid;
ViewBag.CheckButtonStatus = ButtonSubmitted(patid);
var labs = db.Labs.Where(l => l.PatientId == patid && l.Active);
LabIndexViewModel model = new LabIndexViewModel();
model.Labs = labs.ToList();
model.Lab = lab;
SetViewBagLists();
return View(model);
}
Then in my post where it will not save:
[HttpPost]
public ActionResult Create(LabIndexViewModel labindex)
{
ViewBag.DispPatientId = labindex.Lab.PatientId;
Lab lab = labindex.Lab;
try
{
lab.Active = true;
db.Labs.Add(lab);
db.SaveChanges();
return RedirectToAction("Index", "Lab", new { patid = lab.PatientId });
}
catch
{
ViewBag.Phase = new SelectList(StatusList(), "Text", "Value");
ViewBag.Name = new SelectList(db.LabOptions, "Test", "Value", lab.Name);
return View(lab);
}
}
Here is my partial where I submit the data in my view:
#model PamperWeb.Models.LabIndexViewModel
#using (Html.BeginForm("Create", "Lab")) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Lab</legend>
<tr>
<td>
#Html.DropDownList("Name", String.Empty)
#Html.ValidationMessageFor(model => model.Lab.Name)
</td>
<td>
#Html.EditorFor(model => model.Lab.Value)
#Html.ValidationMessageFor(model => model.Lab.Value)
</td>
<td>
#Html.EditorFor(model => model.Lab.Given)
#Html.ValidationMessageFor(model => model.Lab.Given)
</td>
<td>
#Html.EditorFor(model => model.Lab.TimeGiven)
#Html.ValidationMessageFor(model => model.Lab.TimeGiven)
</td>
<td>
#Html.DropDownList("Phase", String.Empty)
#Html.ValidationMessageFor(model => model.Lab.Phase)
</td>
#Html.HiddenFor(model => model.Lab.PatientId)
<td>
<input type="submit" value="Create" />
</td>
</tr>
</fieldset>
}
Anybody have any idea on how to make this work or have a good example?
I didn't realy understand all the question, but I saw something wrong there:
1) Yours PartialView must post a Lab, so make It strongly typed for Lab, because HTML Helpers will generate HTML that the default ModelBinder cannot process to build the model back in the server using LabIndexViewModel:
#model PamperWeb.Models.Lab
#using (Html.BeginForm("Create", "Lab")) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Lab</legend>
<tr>
<td>
#Html.DropDownList("Name", String.Empty)
#Html.ValidationMessageFor(model => model.Name)
</td>
<td>
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model => model.Value)
</td>
<td>
#Html.EditorFor(model => model.Given)
#Html.ValidationMessageFor(model => model.Given)
</td>
<td>
#Html.EditorFor(model => model.TimeGiven)
#Html.ValidationMessageFor(model => model.TimeGiven)
</td>
<td>
#Html.DropDownList("Phase", String.Empty)
#Html.ValidationMessageFor(model => model.Phase)
</td>
#Html.HiddenFor(model => model.PatientId)
<td>
<input type="submit" value="Create" />
</td>
</tr>
</fieldset>
}
2) Change the controller Action Create to receive as parameter the posted Lab:
[HttpPost]
public ActionResult Create(Lab lab)
{
ViewBag.DispPatientId = Lab.PatientId;
try
{
lab.Active = true;
db.Labs.Add(lab);
db.SaveChanges();
return RedirectToAction("Index", "Lab", new { patid = lab.PatientId });
}
catch
{
ViewBag.Phase = new SelectList(StatusList(), "Text", "Value");
ViewBag.Name = new SelectList(db.LabOptions, "Test", "Value", lab.Name);
return View(lab);
}
}
3) Use the ViewModel created to display the labs! Thats the ViewModel master purpose, display complex types in the view! Any other opperation requires creation of a custom ModelBinder to interate throught the request and build the model back in the server.
Hopes this help you! I really got this from the question!
With the help of the comments I was able to figure out the issue. When I added the parameters to the html.beginform it no longer sent my url parameters with the patientid. Not sure why? My normal create view had this so my hidden parameter picked up the value. I ended up setting the value in my controller so the hidden parameter in the form was able to pick it up. Here is what my get index is now which resolved the issue:
public ActionResult Index(int patid = 0, Lab lab = null)
{
ViewBag.Finalize = PatientSubmitted(patid);
ViewBag.DispPatientId = patid;
ViewBag.CheckButtonStatus = ButtonSubmitted(patid);
var labs = db.Labs.Where(l => l.PatientId == patid && l.Active);
LabIndexViewModel model = new LabIndexViewModel();
if (lab == null)
lab = new Lab();
lab.PatientId = patid;
model.Labs = labs.ToList();
model.Lab = lab;
SetViewBagLists();
return View(model);
}
I also found this post helpful in that I found out I can specify a model to send to a partial.

Categories