I have a form where I need to use to buttons(plus and minus) to set count, but I can't figure out how can I bind this counter to model.
I have model looks like:
public class Order
{
public string Name {get; se;}
public int Count {get; set;}
}
Also I have view with form looks like:
#model SushiJazz.Models.ViewModels.OrderViewModel
<div class="container">
#using (Html.BeginForm("CreateOrder", "Order", FormMethod.Post, new { #class = "basket-form" }))
{
<div class="basket-form__input-line">
<label for="b-name" class="basket-form__label">
Name <span class="star-req">*</span>
</label>
#Html.TextBoxFor(model=>model.Name, new { #class="basket-form__input", #id="b-name", #type="tel", #autofocus="autofocus"})
</div>
<div class="basket-counter order-counter static">
<span class="add-del-btn blue">-</span>
<span class="basket-counter-number">2</span>
<span class="add-del-btn blue">+</span>
</div>
}
</div>
So, How can I bind my basket-counter to Model.Count property?
Is it posible?
<span>#Model.Name</span>
And hide the texbox data like this:
#Html.HiddenFor(m => m.Name, new { #readonly = "readonly", #class = "form-control" })
Try this, I have used this in my project and it is working fine.
Related
I am working on a new Asp.Net MVC project and this time to have better control over the static contents of the application, I am planning to store all content as reusable properties in readonly static variables. These values are not going to change throughout the application's lifecycle.
Example of usage:
I have created a class holding all messages in static variables so that if I want to change let's say, the default save message I can change it from here without having a need to change every occurrence in the project. This includes validation messages also. (numbers could grow rapidly, depending upon the size of the project)
Other usages: To store all application-related properties such as version, title, keys, and many more. I am also planning to store the button texts and other UI controls-related properties so that they can be easily customized, such as I don't know maybe CSS classes.
And not to mention, apart from the above I also have a number of static classes such as Data Access Helpers and Utility Functions with some static methods.
Sample Class:
public static class Messages
{
public static class Response
{
public readonly static string SUCCESS = "Process completed successfully";
public readonly static string FAILED = "Process failed";
public readonly static string ERROR = "Some error occured";
public readonly static string OPRNOTPERFORMED = "Operation aborted/failed for some unknown reason. Please contact your administrator";
//LOGIN
public readonly static string USERNOTFOUND = "Invalid username or password";
public readonly static string USERINACTIVE = "User is not active. Please contact your administrator";
public readonly static string NOROLEDEFINED = "User does not have any valid authority to access the application. Please contact your administrator";
public readonly static string FORCELOGOUT = "You have been logged out. Please login again";
//MASTERS
public readonly static string NOSTATESFOUND = "No states found in database. please contact your administrator";
public readonly static string APPCHOICENOTFOUND = "Option not found in the database. Please contact your system administrator.";
//COMPANY
public readonly static string INVALIDCOMPANY = "Please sign out from the application and login again before performing further opreations";
}
public static class Description
{
//COMPANY
public readonly static string INVALIDCOMPANY = "Company value changed between 2 consiquent requests. This happens when you left the page idle for so long. Please login again before performing further operations.";
}
public static class Instructions
{
public readonly static string MANDATORY_FIELDS = "Fields marked with <i class='text-warning-dark fw-bold fs-6'>*</i> cannot be blank.";
}
}
As of now, these are all on paper only. I am willing to take this approach so that I can easily customize the text contents according to different clients' needs. But before that, I have a few doubts to clear.
Does all static variables initialized and stored in memory as we run the web application?
Does all static variables remain in memory throughout the lifecycle of the web application, irrespective of its usage in the current View?
Does the compiler replace the occurrences of the static variable with its actual value at the time of converting the source code into bytecode? (I have seen this in java when I decompiled the class file, wherever I used the static variables, it is replaced with its actual value).
Another Example:
public class Select
{
private static readonly SelectListItem defaultChoice = new SelectListItem { Text = "Select", Value = "" };
public static readonly IEnumerable<SelectListItem> ISACTIVE = new List<SelectListItem>
{
new SelectListItem {Text = "Active", Value = "true"},
new SelectListItem {Text = "Inactive", Value = "false"}
};
private static IList<SelectListItem> STATES;
public static IEnumerable<SelectListItem> GetStates(string sessionHash)
{
if (sessionHash == null)
{
return null;
}
if (STATES == null)
{
StateService stateService = new StateService(sessionHash);
ProcessResponse response = stateService.GetStates();
IList<StateModel> statesModel = (IList<StateModel>)response.Data[0];
STATES = new List<SelectListItem>();
STATES.Add(defaultChoice);
foreach (StateModel state in statesModel)
{
STATES.Add(new SelectListItem { Text = state.Name, Value = state.StateId.ToString() });
}
}
return STATES;
}
public static IEnumerable<SelectListItem> AppChoices(IList<AppChoicesModel> choicesModel)
{
IList<SelectListItem> choices = new List<SelectListItem>();
choices.Add(defaultChoice);
if (choicesModel != null && choicesModel.Count > 0)
{
foreach(AppChoicesModel choice in choicesModel)
{
choices.Add(new SelectListItem { Text = choice.Text, Value = choice.Value });
}
}
return choices;
}
}
Usage in View
#model Cygnus.View.Models.Company.CompanyBranch
#using Cygnus.Data.Constants
#{
Layout = "~/Views/Shared/_LayoutDashboard.cshtml";
ViewBag.Title = Titles.Company.BRANCHT;
ViewBag.SubTitle = Titles.Company.BRANCHST;
var moduleName = Routes.Company.BRANCH;
var isActive = Select.ISACTIVE;
var states = Select.GetStates(Session[Codes.SessionParams.HASH].ToString());
Html.RenderPartial(Routes.Commons.PROCRESPONSE);
}
<div class="container-fluid">
<div class="row">
<!-- left column -->
<div id="#string.Format("{0}Form_Container", #moduleName)" class="col-md-7 mt-1 collapse show">
<!-- general form elements -->
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">#ViewBag.SubTitle</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
#using (Html.BeginForm(moduleName, Routes.Company.CONTROLLER, FormMethod.Post, new { #name = moduleName }))
{
#Html.HiddenFor(model => model.CompanyId)
#Html.HiddenFor(model => model.CompanyBranchId)
#Html.AntiForgeryToken()
<div class="card-body">
<div class="row gx-3">
<div class="col-10">
<i class="fas fa-info-circle text-info mr-2"></i>#Html.Raw(#Messages.Instructions.MANDATORY_FIELDS)
</div>
<div class="col-2">
<button class="btn btn-block btn-info btn-flat size-width-auto float-right" value="#Codes.ButtonValue.ADD" name="#Codes.ButtonGroupName.ACTION" ><i class="fas fa-plus-square fa-1xl align-middle mr-2"></i><span class="align-middle">#Codes.ButtonValue.NEW</span></button>
</div>
</div>
<div class="row gx-3 mt-3">
<div class="input-group-sm col">
<label for="Name" class="fw-semibold">#Html.DisplayNameFor(model => model.Name)</label>
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control input-required", #placeholder = "Branch Name" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger fs-6-5" })
</div>
<div class="input-group-sm col-4">
<label for="Code" class="fw-semibold">#Html.DisplayNameFor(model => model.Code)</label>
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control input-required", #placeholder = "Branch Code" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger fs-6-5" })
</div>
</div>
<div class="row gx-3 mt-5px">
<div class="input-group-sm col">
<label for="State" class="fw-semibold">#Html.DisplayNameFor(model => model.State)</label>
#Html.DropDownListFor(model => model.State, states, new { #class = "form-control input-required" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger fs-6-5" })
</div>
<div class="input-group-sm col-2">
<label for="Pincode" class="fw-semibold">#Html.DisplayNameFor(model => model.Pincode)</label>
#Html.EditorFor(model => model.Pincode, new { htmlAttributes = new { #class = "form-control input-required", #placeholder = "Pincode" } })
#Html.ValidationMessageFor(model => model.Pincode, "", new { #class = "text-danger fs-6-5" })
</div>
<div class="input-group-sm col">
<label for="BranchType" class="fw-semibold">#Html.DisplayNameFor(model => model.BranchType)</label>
#Html.DropDownListFor(model => model.BranchType, Model.BranchTypeList, new { #class = "form-control input-required" })
#Html.ValidationMessageFor(model => model.BranchType, "", new { #class = "text-danger fs-6-5" })
</div>
</div>
<div class="row gx-3 mt-5px">
<div class="input-group-sm col">
<label for="IsActive" class="fw-semibold">#Html.DisplayNameFor(model => model.IsActive)</label>
#Html.DropDownListFor(model => model.IsActive, isActive, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.IsActive, "", new { #class = "text-danger fs-6-5" })
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" value="#Codes.ButtonValue.SAVE" name="#Codes.ButtonGroupName.ACTION" class="btn btn-success px-5">#Codes.ButtonValue.SAVE</button>
<div>#Html.ValidationSummary(true, "", new { #class = "text-danger" })</div>
</div>
}
</div>
<!-- /.card -->
</div>
<div class="col-md mt-1">
#{
Html.RenderAction(Routes.Company.BRANCHLIST, Routes.Company.CONTROLLER);
}
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/Scripts/Cygnus/Company.js")
<script>
$(function () {
var tableId = "#listOfCompanyBranch";
initDataTableWithDefaultToolbar(tableId, '#moduleName');
attachRowDataEvenOnATag(tableId);
});
function onRowClicked(rowData, row) {
let formElement = $("##string.Format("{0}Form_Container",moduleName)");
if ($(formElement).is('.collapse:not(.show)'))
$(formElement).collapse("show");
document.getElementById("CompanyBranchId").value = $(row).attr("data-branch");
document.getElementById("CompanyId").value = $(row).attr("data-company");
FillFormControls(formArr["#moduleName"], rowData);
$("#IsActive").val((rowData[13]).toLocaleLowerCase());
}
</script>
}
Does Having Hundreds of Readonly Static Variables Cause Performance
Issues?
No. The variables in your example are a few bytes each. Let's say you have 500 variables, and they are 20 bytes each. That would be 10KB. Modern web servers generally have several gigabytes of memory, so it is unlikely that you face any performance issue because you are caching 10KB of data. See here for more info about static variables.
IMO, the main issue with having too many static types (class/variable) is that you don't know where to find them. In the examples that you have provided, it seems like you are hardcoding some constants into static variables. IMO that’s fine, provided:
You don’t define configuration variables as constants (things like connection strings, which are environment dependent)
You are using a logical approach to group these constants, so they are easy to find
I would try to limit the size of such constants (not because of performance but to keep the code clean)
Looking at your code, there might be more elegant ways to achieve this, for example you can define an interface called IResponse:
interface IResponce
{
short Code { get; }
string CssColor { get; }
string Message { get; }
}
and define different classes for response types, for example:
public class SuccessResponse : IResponse
{
public short Code => 0;
public string CssColor => "green";
public string Message => "Process completed successfully";
}
public class FailureResponse : IResponse
{
public short Code => 1;
string CssColor => "red";
public string Message => "Process failed";
}
So I have a list of clients in a database with various information about them. I need to print all of them out with a slidedown form with their current information already there, and the ability to add or change it.
I am able to print out all the clients and their info but when I try to edit the form it is disabled even though there is no disabled attribute set.
Here is the controller
public ActionResult Index()
{
var context = new U2XPlanningAutomationToolEntities();
string query = "SELECT * FROM Clients";
IEnumerable<Client> data = context.Database.SqlQuery<Client>(query);
List<Client> clients = new List<Client>(data);
ViewBag.Clients = clients;
string email = Session["email"] as string;
if (!String.IsNullOrEmpty(email))
{
return View();
}
return View("../Account/Login");
}
The View
#foreach (var client in ViewBag.Clients)
{
string plan_changes = client.plan_changes;
string critical_milestones = client.critical_milestones;
string pdd = client.pdd;
string inbound = client.inbound;
string outbound = client.outbound;
string other = client.other;
<div class="row client">
<div class="col-sm-3"><span id="#client.id" class="glyphicon glyphicon-plus dropdownBtn"></span><p>#client.name</p></div>
<div class="col-sm-3"><p>#client.oep_start</p></div>
<div class="col-sm-3"><p>#client.oep_end</p></div>
<div class="col-sm-3 text-right"><button id="#client.id" class="btn btn-primary delete-client">Delete</button></div>
<div class="col-sm-12 slider" id="slider_#client.id">
#using (Html.BeginForm("UpdateClient", "Home", FormMethod.Post))
{
<div class="col-sm-4">
<input type="hidden" name="id" value="#client.id" />
#Html.LabelFor(c => c.plan_changes, "Plan Changes")
#*<textarea name="plan_changes" class="form-control" cols="20" rows="2">#plan_changes</textarea>*#
#Html.TextArea("plan_changes", plan_changes, new { #class = "form-control" })
#Html.LabelFor(c => c.critical_milestones, "Critical Milestones")
#Html.TextArea("critical_milestones", critical_milestones, new { #class = "form-control" })
</div>
<div class="col-sm-4">
#Html.LabelFor(c => c.pdd, "Plan Document Design")
#Html.TextArea("pdd", pdd, new { #class = "form-control" })
#Html.LabelFor(c => c.inbound, "Inbound")
#Html.TextArea("inbound", inbound, new { #class = "form-control" })
</div>
<div class="col-sm-4">
#Html.LabelFor(c => c.outbound, "Outbound")
#Html.TextArea("outbound", outbound, new { #class = "form-control" })
#Html.LabelFor(c => c.other, "Other")
#Html.TextArea("other", other, new { #class = "form-control" })
</div>
<div class="col-sm-12 text-center">
<input type="submit" value="Update" name="update" class="btn btn-primary" />
</div>
}
</div>
</div>
}
If my approach seems weird to you it might be because I am brand new to MVC ASP.NET, I am coming from a PHP background.
Thanks in advance!
Please use a IEnumerable<Client> in you view instead of putting it into a viewbag. Can you try to pass the id in the Html.BeginForm. Do you have an UpdateClient method in your HomeController class?
I have added a list to my view model but when I access it in a foreach loop in the view it throws:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_MyActivationCampaign_Campaign.ExecuteAsync() in Campaign.cshtml
+ foreach(var dp in Model.DpRestrictedList)
This is the list I have added:
public List<DpRestricted> DpRestrictedList { get; set; } = new List<DpRestricted>()
{
new DpRestricted(){DpId = 1, Name = "Post Restricted" },
new DpRestricted(){DpId = 2, Name = "Unrestricted" },
new DpRestricted(){DpId = 3, Name = "Customer Restricted" }
};
}
public class DpRestricted
{
public int DpId { get; set; }
public string Name { get; set; }
}
and I am trying to loop over it like this:
<div class="row">
<fieldset>
<legend>Delivery Methods</legend>
<div id="radio">
#*<input type="radio" id="new-method">
<label for="new-method">New Method</label>
<input type="radio" id="dm-101" checked="checked">
<label for="dm-101">DM_101</label>
<input type="radio" id="delivery-method-2">
<label for="delivery-method-2">Delivery Method 2</label>*#
#{
foreach(var dp in Model.DpRestrictedList)
{
#Html.RadioButtonFor(model => model.DeliveryPointRestrictionId, dp);
}
}
</div>
</fieldset>
</div>
Using statement and example:
#model WorkstreamX.Web.Core.ViewModels.ActivationCampaignViewModel
...
<div class="col-md-4">
<label for="headline">Campaign</label>
#Html.EditorFor(model => model.CampaignName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CampaignName)
</div>
The above is the using statement in the view and an example of how it is already being used elsewhere in it. When I check it is not just the list that is null but the Model in the loop statement is also null. Is it a case of me needing to new up the view model in the controller at this point? That is what I am about to try I just wanted to state this question and maybe find out why this is happening. Any advice here greatly appreciated.
[edit] How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.
Your code should be like the below one.
Public ActionResult GetEmployee()
{
var employee = GetEmployee();
return View(employee);
}
#model IEnumerable<Appname.ViewModel.Employee>
#{
foreach(var data in Model) {}
}
How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.
I am trying to create sub category for categories. User first select the categories from dropdownlist and then type the subcategory name and clicks submit. Even though dropdownlist elements are properly fill the dropdown list. When I click submit button It creates error. How can I solve this?
My View:
#model CETAPPSUGG.Models.CategorySubCategoryModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.selectedId, new { id = "3" });
// #Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SubCatagories</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SubCategory.SubCategoryName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubCategory.SubCategoryName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SubCategory.SubCategoryName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Upper cat: <div class="col-md-10">
#Html.DropDownListFor(Model => Model.Categories, Model.categoryList)
</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")
</div>
My Controller:
public ActionResult Create()
{
var categories = db.Categories.ToList();
CategorySubCategoryModel deneme = new CategorySubCategoryModel();
var list = new List<SelectListItem>();
deneme.Categories = categories;
foreach (Categories c in categories)
{
list.Add(new SelectListItem() { Text = c.CategoryName, Value = c.Id.ToString() });
}
deneme.categoryList = list;
return View(deneme);
}
// POST: SubCatagories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
// [ValidateAntiForgeryToken]
public ActionResult Create( CategorySubCategoryModel model)
{
string strDDLValue = model.selectedId;
SubCatagories newSubCategory = new SubCatagories();
Categories cat = new Categories();
cat = db.Categories.Find(Convert.ToInt32(strDDLValue));
// cat = db.Categories.Find(Convert.ToInt32(strDDLValue));
newSubCategory.SubCategoryName = model.SubCategory.SubCategoryName;
newSubCategory.UpperCategory = Convert.ToInt32(strDDLValue);
newSubCategory.Categories = cat;
db.SubCatagories.Add(newSubCategory);
db.SaveChanges();
return View();
}
My Model
namespace CETAPPSUGG.Models
{
public class CategorySubCategoryModel
{
SubCatagories SubCatagories { get; set; }
public IEnumerable<Categories> Categories { get; set; }
public IEnumerable<SubCatagories> SubCategories { get; set; }
public IEnumerable<SelectListItem> categoryList { get; set; }
public SubCatagories SubCategory { get; set; }
public string selectedId;
}
}
It creates error in view
You have a bunch of problems here.
Your primary problem is that you are not passing a model back to the View on post, thus the model is null. So, when you attempt to dereference items from the model in the View, a null reference is generated.
First, you are using selectedId but do not set this anywhere. It doesn't get set by magic. What you probably want is #Html.DropDownListFor(model => model.selectedId, Model.categoryList) (note the lowercase m in model in the first parameter, and uppercase M in the second)
Second, don't use a Model in your lambda in the DropDownListFor, use the lowercase model, because uppercase Model is reserved for the actual Model instance. If you want to reference the Model instance, then do something like DropDownListFor(_ => Model.Foo, Model.Foos). Note that I replaced the Model before the lambda with an underscore or some other value that is not Model. Frankly i'm surprised this even works, but there's probably a scoping rule here that overrides the outer Model. Avoid this because it can cause you confusion down the road.
Third, you are passing an IEnumerable to the DropDownListFor as the selected item variable, this won't work on a number of levels. This needs to be a single string value in most cases (sometimes a numerical one, but always a single more basic type that can have ToString() called on it and get a sensible string since DropDownListFor can't display complex objects).
Fourth, You also need to re-populate your DropDownListFor in the Post action, because the contents of a dropdownlist are not posted back, and thus will be null in the model. This, along with the SubCategory derefences in your view are ultimately what is generating the Null Reference exception.
You also need to pass the model back to your view in the Post, but as stated above, it needs to be re-initialized with the Categories as well as SubCategories.
There are probably more problems here, but fix these and you should be on your way.
I have a model called Result. Suppose this has 4 fields, like student_id, marks, status, remarks.
Now I have a view in which student listing is shown. In front of each student, there is a button for enter marks of exam. On clicking on button a pop-up will open and there will be 2 fields student_id, marks and 2 buttons 'pass' and 'fail'.
On clicking on fail button another pop-up will appear for enter remarks only.
Now my question is that, how can I retain values of first pop-up on second pop-up, As on clicking on 'submit' button of second pop-up, I will save all the details.
I know a way to do this using hidden fields in second pop-up. Is there any other way to do this?
Model classes are:
1. User (id, name, f_name, address...)
2. Result (student_id, marks, grade, remarks)
Student List view
#{
List<User> Student = (List<User>)ViewData["Student"];
}
<table id="table_id">
<tr>
<th class="dbtc">S.No.</th>
<th class="dbtc">Student Name)</th>
<th style="width: 110px">Operate</th>
</tr>
#foreach (User usr in Student)
{
int index = Student.IndexOf(usr);
<tr>
<td class="dbtc">
#(Student.ToList().IndexOf(usr) + 1)
</td>
<td>
#Html.ActionLink(usr.FirstName + " " + usr.LastName, "Details", "User", new { id = usr.Id }, null)
</td>
<td>
#Ajax.ActionLink("Examine", "Result", new { id = Model.Id, userId = usr.Id }, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "divPopup",
InsertionMode = InsertionMode.Replace,
OnSuccess = "openPopup('Examine Content')"
})
</td>
</tr>
First Partial view of examine
#model ComiValve.Models.Result
#using (Html.BeginForm("ExamPass", "Student", new { #id = (int)ViewBag.id, userId = (int)ViewData["UserId"] }, FormMethod.Post))
{
<div id="divExamAdvice"></div>
<div class="editor-label">
#Html.DisplayNameFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Marks)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Grade)
</div>
<div class="login_submit_div">
<input type="submit" value="Pass" />
#Ajax.ActionLink("Fail", "ExamAdvice", new { id = (int)ViewBag.id, userId = (int)ViewData["UserId"] }, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "divPopup",
OnSuccess = "openPopup('Exam Advice')"
})
</div>
}
Second partial view for remaks (when user click on fail, then this view will open.)
#model ComiValve.Models.ExamContent
#using (Html.BeginForm("ExamFail", "Student", new { id = Model.id }, FormMethod.Post))
{
<div id="divExamAdvice"></div>
<div class="editor-label">
#Html.DisplayNameFor(model => model.Remarks)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Remarks)
</div>
<div class="left">
<input type="submit" value="Confirm Fail" />
</div>
}
Methods of Controller
public virtual ActionResult ExamContent(int id, int userId)
{
ViewBag.IsApprove = true;
ViewBag.UserId = userId;
ViewBag.id = id;
return PartialView("ExamContent");
}
public virtual ActionResult ExamAdvice(int id, int userId)
{
ViewBag.IsApprove = true;
if (Request.IsAjaxRequest())
{
Result result = new Result();
result.id = id;
result.User = db.Users.Find(userId);
return PartialView("ExamAdvice", result);
}
else
{
return RedirectToAction("Index");
}
}
Why are you passing the model between partial views. You can create a single Model and use it on both the views. In case of having two different tables, create the two different "Lists" of "Table" type. Like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
namespace LearningMVCapp.Models
{
public class Data
{
public List<tbl_Dept> lstDepatrment;
public List<tbl_employees> lstEmployees;
//other properties
}
}
You can also use session instead of hidden fields, refer this link http://www.dotnet-tricks.com/Tutorial/mvc/906b060113-Controlling-Session-Behavior-in-Asp.Net-MVC4.html.