This article is collection of "How Tos" that I came across while building my first ASP.NET MVC application. This article can be useful for developers who are migrating from web forms to MVC and planning to develop their first ASP.NET MVC application. (It may not be that useful for beginners).
I admit that I goggled extensively and collected information from various resources but most important are:
-
How to clear textbox value using jquery?
$("#CandidateName").val('');
-
How to reset dropdown list using jquery
$('#TestBatchId option:eq(0)').attr('selected', 'selected');
-
How to apply css style to helper method in MVC
@Html.TextAreaFor(model => model.Que, new { @class = "form-control" })
-
How to generate auto password
String Password = System.Web.Security.Membership.GeneratePassword(6,0)
-
How to submit form using javascript
document.forms[0].submit();
-
How to fix position of div (in bottom right corner)?
<div style="position: fixed; right: 0; bottom:0">
</div>
-
How to access viewbag value in javascript
var testDuration = '@ViewBag.TestDuration';
-
How to declare variable inside html table using razor.
@{int srNo = 1; }
-
How to display decimal value on view? Or
-
Hot to specify floating point number to display in javascript?
item.Percentage.toFixed(2)
-
How to Create authentication cookie
FormsAuthentication.SetAuthCookie(logon.UserName, false);
-
How to make sure that at least one checkbox is checked using JQuery?
<script>
$("#btnSubmit").click(function (e) {
if ($("#gender:checked").length === 0) {
e.preventDefault();
alert("select gender");
return false;
}
});
</script>
-
How to call function on selecting checkbox
$("input[type='checkbox']").change(function () {
alert("Hello");
});
-
How to check if dropdownlist item is selected or not?
if($("#RoomId").val() === "")
{
alert("Room Not Selected!");
return;
}
-
How to get selected value of dropdownlist using jquery
var id = parseInt($("#RoomId").val());
-
How to get selected text of dropdownlist using jquery
var roomName = $("#RoomId option:selected").text()
-
How to generate non repeating random numbers
List<int> nos = new List<int>();
Random r = new Random();
do
{
int no = r.Next(1, 11);
if (!nos.Contains(no))
nos.Add(no);
} while (nos.Count != 10);
-
How to call javascipt function once view is loaded / on form load event
$(document).ready( function () {
fun1 ();
}
-
How to align div in center vertically and horizontally?
div
{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
-
How to display only date and ignore time while working with dates in MVC
Model:
[DataType(DataType.Date)]
public Nullable<System.DateTime> JoiningDate { get; set; }
Razor / View
@Html.TextBoxFor(model => model.JoiningDate, "{0:dd/MM/yyyy}"})
-
How to get parent of element using jquery? Or
-
How to get second or higher level of parent of element using jquery?
$(this).parents(':eq(6)').css({ "border": "2px solid red" });
-
How to declare variable in view using razor
@{int srNo = 1; }
-
How to Use special character like html tag in razor in MVC?
Html can be included in razor using @: for example:
@:<td>
-
How to pass select list to dropdown list from controller to view? Or
-
How to use dropdown list in MVC?
Requirement: While creating TestBatch for Specific Test all available tests should get populated in dropdown list, so that one can be selected from. Solution: There are more than one ways to do it. I have used following technique.
- First create view model (View Model is class specifically created to pass data from controller to view. You should create separate folder ‘ViewModel’ to keep all your view models at one place.)
public class SelectTestViewModel
{
public int TestId { get; set; }
public string TestName { get; set; }
public bool IsSelected { get; set; }
}
- Create List of SelectTestViewModel and populate it with all tests from database.
- Create object of SelectList class passing list created in above step . Save this object to viewbag using key TestId. We are intentionally using TestId as a key. We will be using same name for dropdown list in view to take advantage of MVC conventions and binding.
- SelectList is specialised class to be used with dropdown lists or any list control. It resides in System.Web.Mvc namespace
- First parameter is list of Tests, second is Value field, Third is Text field and last is pre-selected item in this case it is null
public ActionResult Create()
{
PopulateTestData();
return View();
}
private void PopulateTestData()
{
var allTests = unitOfWork.TestRepository.Get();
var allTestsViewModel = new List<selecttestviewmodel>();
foreach (var test in allTests)
{
allTestsViewModel.Add(new SelectTestViewModel
{
TestId = test.TestId,
TestName = test.TestName,
IsSelected = false
});
}
ViewBag.TestId = new SelectList(allTestsViewModel, "TestId", "TestName", null);
}
</selecttestviewmodel>
- In view use helper method. Fist parameter is Name of control which is same as key in ViewBag so automatically will get bonded to SelectList object. Second parameter is just text to display on dropdown list by default.
- After submitting form selected TestId will get submitted and will automatically bind to TestId property of model entity.
@Html.DropDownList("TestId","--Select Test--")
-
How to have star rating input or display?
Use rateit plugin
Refer: http:
-
How to create calander ui for appointment or booking type of application?
Use FullCalendar and Moment plugins
http: http:
-
How to use checkboxes in MVC
Requrement: Question can be applicable in multiple tests. So while uploading question I should get chance to select multiple tests for the question. Also note that there is many-to-many relationship between ‘Test’ and ‘Question’; Junction table TestQuestion manages this relationship. It has only two columns TestId and QuestionId. For detail refer to question “How to manage many-to-many relationship in entity framework”
Solution: All available tests should be populated in checkbox so that user can able to select multiple tests for question
- Question Entity
public class Question
{
public Question()
{
this.Tests = new HashSet<Test>();
}
public int QuestionId { get; set; }
public virtual ICollection<Test> Tests { get; set; }
}
- Test Entity
public class Test
{
public Test()
{
this.Questions = new HashSet<Question>();
}
public int TestId { get; set; }
[Required]
public string TestName { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
- Specify many-to-may relationship in datacontext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Test>()
.HasMany(t => t.Questions)
.WithMany(t => t.Tests)
.Map(m =>
{
m.ToTable("TestQuestion");
m.MapLeftKey("TestId");
m.MapRightKey("QuestionId");
});
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
- Create SelectTestViewModel
public class SelectTestViewModel
{
public int TestId { get; set; }
public string TestName { get; set; }
public bool IsSelected { get; set; }
}
- Write PopulateAvailaleTestData() method: While writing this method we are writing it keeping in mind requirement of edit mode also; where we need to show applicable tests for questions as selected. So this method accepts Question as parameter and fetches currently selected tests. This parameter is not useful for create operation as there are no selected tests and returns null.
private void PopulateAvailableTestData(Question question) {
var allTests = unitOfWork.TestRepository.Get();
var assignedTests = new HashSet<int>(question.Tests.Select(t => t.TestId));
var allTestsViewModel = new List<SelectTestViewModel>();
foreach (var test in allTests)
{
allTestsViewModel.Add(new SelectTestViewModel
{
TestId = test.TestId,
TestName = test.TestName,
IsSelected = assignedTests.Contains(test.TestId)
});
}
ViewBag.Tests = allTestsViewModel;
}
- Write Get Action Method for Create()
public ActionResult Create()
{
var question = new Question();
question.Tests = new List<Test>();
PopulateAvailableTestData(question);
return View();
}
- Write Post Action Method for Create(): Note that parameter ‘selectedTests’ is same as of name of checkboxes in view. So that checkbox selected values i.e TestIds will get submitted to selectedTests array.
[HttpPost]
public ActionResult Create(Question question, string[] selectedTests)
{
if(selectedTests != null)
{
question.Tests = new List<Test>();
foreach(var test in selectedTests)
{
var testToAdd = unitOfWork.TestRepository.GetByID(int.Parse(test));
question.Tests.Add(testToAdd);
}
}
if(ModelState.IsValid)
{
unitOfWork.QuestionRepository.Insert(question);
unitOfWork.Save();
return RedirectToAction("Index");
}
return View();
}
- View to create question: foreach loop will display checkboxes for all available tests. If condition to display checkboxes in three columns only. For create operation line @(Html.Raw(test.IsSelected ? "checked=\"checked\"" : "")) can be removed it is required for edit operation. It selects checkbox for currently applicable tests.
<table>
<tr>
@{
int cnt = 0;
List<OnlineTest.ViewModel.SelectTestViewModel> tests = ViewBag.Tests;
foreach (var test in tests)
{
if (cnt++ % 3 == 0)
{
@:</tr><tr>
}
@:<td>
<input class="" type="checkbox"
name="selectedTests"
id="selectedTests"
value="@test.TestId"
@(Html.Raw(test.IsSelected ? "checked=\"checked\"" : "")) />
@: @test.TestName
@:</td>
}
@:</tr>
}
</table>
<span style="display: none;"> </span>
-
How to use multiple groups of checkboxes in MVC? Or
-
How to submit multiple groups of checkboxes? Or
-
How to populate random questions for different users? Or
-
How to generate random numbers with in specific range? Or
-
How to use Dictionary?
I wanted to render one page question paper i.e. if there are 25 questions all should come one below other with their options and question can have multiple answers so options to be displayed using checkboxes. Now problem was how to generate group of this options and how to identify which set of options selected for which question
- Create OptionsViewModel
public class OptionsViewModel
{
public int OptionId { get; set; }
public string Option { get; set; }
public bool IsSelected { get; set; }
}
- Create QuestionWithOptionsViewModel
public class QuestionWithOptionViewModel
{
public int QuestionId { get; set; }
public string Question { get; set; }
public List<OptionsViewModel> Options { get; set; }
public QuestionWithOptionViewModel()
{
Options = new List<OptionsViewModel>();
}
}
- Get QuestionPaper()
public ActionResult QuestionPaper()
{
int testId = (int)Session["TestId"];
Test Test = unitOfWork.TestRepository.Get(t => t.TestId == testId).FirstOrDefault();
var questions = Test.Questions;
List<QuestionWithOptionViewModel> questionsWithOptions = new List<QuestionWithOptionViewModel>();
QuestionWithOptionViewModel queWithOpt;
Dictionary<int, string> Answers = new Dictionary<int, string>();
List<int> nos = new List<int>();
Random r = new Random();
do
{
int no = r.Next(0, Test.Questions.Count);
if (!nos.Contains(no))
nos.Add(no);
} while (nos.Count != Test.TotalQuestions);
foreach(int no in nos)
{
Question question = Test.Questions.ElementAt(no);
string ansStr = "";
queWithOpt = new QuestionWithOptionViewModel();
queWithOpt.QuestionId = question.QuestionId;
queWithOpt.Question = question.Que;
foreach (var optionItem in question.Options)
{
queWithOpt.Options.Add(new OptionsViewModel{
OptionId = optionItem.OptionId,
Option = optionItem.AnsOption,
IsSelected = false,
});
if(optionItem.IsAnswer == true)
{
if (ansStr.Length == 0)
ansStr = optionItem.OptionId.ToString();
else
ansStr += "," + optionItem.OptionId;
}
}
questionsWithOptions.Add(queWithOpt);
Answers.Add(question.QuestionId, ansStr);
}
TempData["Answers"] = Answers;
return View(questionsWithOptions);
}
- Must know about check boxes:
- Browser doesn’t submit anything for unselected checkbox. Neither null nor false.
- Brower submits comma separated values for selected checkboxes with same name.
- On server side values can be accepted in FormCollection object. Checkboxes Name property used as key for set of selected checkboxes.
- Values can be accessed as Collection[i]
- Key can be access as Collection.Keys[i]
- Post QuestionPaper(): When user submits question paper all the selected option will be submitted to collection object.
[HttpPost]
public ActionResult QuestionPaper(FormCollection collection)
{
Dictionary<int, string=""> Answers = (Dictionary<int, string="">)TempData["Answers"];
int marks = 0;
for (int i = 1; i < collection.Keys.Count; i++ )
{
string rightAnswer = Answers[int.Parse(collection.Keys[i])];
string userAnswer = collection[i];
if(userAnswer == rightAnswer)
{
marks++;
}
}
}
</int,></int,>
- View: Note that options use OptionId as value and QuestionId as Name. That means if a Question have 4 options then all options will have same name.
<div id="@srNo" class="panel-collapse collapse in">
<div class="panel-body">
<table class="table">
@{int opNo = 0;}
@foreach (var option in item.Options)
{
<tr>
<td>
<input class="ansoption" type="checkbox" name="@item.QuestionId" value="@option.OptionId" />
@option.Option
</td>
</tr>
opNo++;
}
</table>
</div>
</div>
-
How to do AJAX call from dropdownlist? Or
-
Hot to display data in table / grid format? Or
-
How to serialize data as JSON?
Requirement:Dropdown list populated with all batches. Selecting batch should submit batch id asynchronously to action.
- ScoreJSonModel:Data will be stored in object of this class and then will serialize to JSON
public class ScoreJsonModel
{
public string TestName { get; set; }
public string TestDate { get; set; }
public int TotalQuestions { get; set; }
public int TotalMarks { get; set; }
public string Duration { get; set; }
public int TestTakerId { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
public int ScoredMarks { get; set; }
public double Percentage { get; set; }
}
- ScoreController:
public class ScoreController : Controller
{
UnitOfWork unitOfWork = new UnitOfWork();
public ActionResult Index(int? TestBatchId = null)
{
if(TempData["TestBatchId"] != null)
TestBatchId = (int)TempData["TestBatchId"];
PopulateBatches(TestBatchId);
return View();
}
public JsonResult BatchwiseScore(int? TestBatchId = null)
{
if (TestBatchId != null)
{
TempData["TestBatchId"] = TestBatchId;
}
PopulateBatches(TestBatchId);
var scores = unitOfWork.ScoreRepository.Get(tb=>tb.TestTaker.TestBatchId == TestBatchId,s => s.OrderByDescending(m=>m.TestScore));
List<ScoreJsonModel> scoresJsonModelList = new List<ScoreJsonModel>();
foreach (var s in scores)
{
ScoreJsonModel scoreJsonModel = new ScoreJsonModel
{
TestName = s.TestTaker.TestBatch.Test.TestName,
TestDate = s.TestTaker.TestBatch.Test.Date.ToShortDateString(),
TotalQuestions = s.TestTaker.TestBatch.Test.TotalQuestions,
TotalMarks = s.TestTaker.TestBatch.Test.TotalMarks,
Duration = s.TestTaker.TestBatch.Test.Duration.ToString(),
TestTakerId = s.TestTakerId,
UserId = s.TestTaker.LoginId,
Name = s.TestTaker.TestTakerInfo.FirstName + " " + s.TestTaker.TestTakerInfo.LastName,
ScoredMarks = s.TestScore,
Percentage = (float)s.TestScore / (float)s.TestTaker.TestBatch.Test.TotalMarks * 100.0
};
scoresJsonModelList.Add(scoreJsonModel);
}
return Json(scoresJsonModelList, JsonRequestBehavior.AllowGet);
}
private void PopulateBatches(object selectedBatch = null)
{
var batches = from batch in unitOfWork.TestBatchRepository.Get() select new { batch.TestBatchId, batch.TestBatchName };
ViewBag.TestBatchId = new SelectList(batches, "TestBatchId", "TestBatchName", selectedBatch);
}
}
-
How to save json data using jquery ajax in MVC?
MVC is smart enough to parse json data to your model object. No extra step need to be done. (At least for me it worked) Only take care while creating json object in javascript function; json keys should match with model properties. Refer following sample code.
Model:
public partial class Booking
{
public int BookingID { get; set; }
public int RoomID { get; set; }
public string BookedBy { get; set; }
public string MeetingTitle { get; set; }
public System.DateTime BookingDate { get; set; }
public System.DateTime FromTime { get; set; }
public System.DateTime ToTime { get; set; }
public virtual Room Room { get; set; }
}
Script in view
$('#btnSaveMeeting').click(function () {
$('#popupForm').hide();
var bookedBy = "ODL/474";
var dataRow = {
'BookedBy': bookedBy,
'RoomID': $("#RoomId").val(),
'BookingDate': localStorage["bookingDate"],
'FromTime': localStorage["startTime"],
'ToTime': localStorage["endTime"],
'MeetingTitle': $("#MeetingTitle").val()
}
$.ajax({
type: 'POST',
url: '@Url.Action("SaveMeeting", "Room")',
data: dataRow,
success: function (response) {
if (response == 'True') {
alert('Meeting Saved!');
}
else {
alert('Error, could not save meeting!');
}
}
});
Controller
public bool SaveMeeting(Booking BookingDetails)
{
resdemoEntities dc = new resdemoEntities();
dc.Bookings.Add(BookingDetails);
dc.SaveChanges();
return true;
}
-
How to use datetimepicker to enter dates?
-
How to change format of datetimepicker to yy-mm-dd?
Make sure that you have referred following three jquery files:
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
Html:
<input type="text" id="TestDate" name="TestDate" />
Script: Type in bottom of view
<script language="javascript">
$("#TestDate").datepicker({ dateFormat: "yy-mm-dd" });
</script>
-
How to put validation for Duration textbox to check pattern in hh:mm:ss format?
-
How to provide masked text box to enter duration or date like formats in MVC?
-
How to use Jquery Masked plugin?
- Install Jquery Masked plugin using package manager
- Refer it in view
<script src="~/Scripts/jquery.maskedinput-1.3.1.min.js"></script>
- HTML/Body:
@Html.EditorFor(model => model.Duration) or
<input type="text" id="Duration" name="Duration" />
- Script: Add to buttom of view
<script>
$("#Duration").mask("99:99:99");
</script>
-
check http:
-
how to create thumbnail list in MVC using bootstrap?
<div class="row">
@foreach (var item in Model)
{
<div class="col-sm-2">
<a href="#" class="thumbnail">
<img src="@item.ImageUrl" alt="@item.EmpID" />
</a>
<div class="caption text-center">
<h5>@item.EmpName</h5>
</div>
</div>
}
</div>
-
How to persist filter value between page redirects?
I filtered data on page1 then visited page2 now when I come back to page1 it should show filtered list. One of the soultion is using TempData. TempData object resides in server memory only till we access it once. So it is memory efficient.
public ActionResult Index(int? testId = null)
{
if (TempData["TestId"] != null)
testId = (int)TempData["TestId"];
if (testId != null)
{
TempData["TestId"] = testId;
}
PopulateTestDropDown(testId);
Question[] questions = unitOfWork.QuestionRepository.Get(q => q.Tests.Any(t=>t.TestId == testId)).ToArray();
return View(questions);
}
-
where to save values from javascript for future use?
-
How to use session storate / localstorage / webstorage in HTML5
sessionStorage["bookingDate"] = moment(start).format();
sessionStorage["startTime"] = moment(start).format("hh:mm a");
sessionStorage["endTime"] = moment(end).format("hh:mm a");
var dateTimeDetails = moment(sessionStorage["bookingDate"]).format("ddd MMM D") + " " + sessionStorage["startTime"] + " - " + sessionStorage["endTime"];
$('#BookingDateTime').text(dateTimeDetails);
Refer: http:
-
How to compare only dates in linq query?
use System.Data.Entity.DbFunctions.TruncateTime();
var result = (from meeting in dc.Bookings
where DbFunctions.TruncateTime(meeting.BookingDate) >= DbFunctions.TruncateTime(fromDate) && DbFunctions.TruncateTime(meeting.BookingDate) <= DbFunctions.TruncateTime(toDate)
select meeting).ToList();
-
How to write left outer join query in linq?
To write left outer join you need to use two keywords:
- into
- DetaultIfEmpty
var result = from emp in dc.EmployeeDetails
join review in dc.ReviewManager on emp.EmpID equals review.EmpID into t
from rt in t.DefaultIfEmpty()
select new TeamMemberViewModel {EmpName = emp.EmpName, ManagerRating = rt.Rating != null ? rt.Rating : 0 };
-
How to enable Code first migration? Or
-
How to update database schema without deleting data while using code first approach? Or
-
How to enable Code first migration when context class is in class library project? Or
-
How to update database after changing entity classes?
Updating database for entity changes is three step process. We have to use following three commands Enable-Migrations: Enables database for code-first migration. This step is one time step. Once database is enabled next time only execute second and third step. Add-Migration: Creates script file with all the changes in entity classes Update-Database: Executes script created using Add-Migration command (in previous step) on database to actually upsize database. In my case I had two projects.
- OnlineTest: ASP.NET MVC Web application
- OnlineTestDomain: Domain model for OnlineTest. With DAL and Entity classes and DbContext class. As DbContext class is in separate class library we have to specify it while executing all above commands.
Following are the commands that I used
Enable-Migrations –ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose
Add-Migration -ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose Migration1
Update-Database -ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose
-
How to create one-to-one relationship in entity framework code first ? Or
-
How to disabled auto increment in code first?
Requirement: There are two tables TestTaker and TestTakerInfo having one-to-one relationship
- TestTaker: Holds automatically created Login Ids and Passwords and TestTakerId
- TestTakerInfo: To save information about TestTaker like Name, Contact no etc. This information will be filled by test taker after logging in to system
- Table structure is as follow
- Important:
- TestTakerInfo Table doesn’t have auto-incremented TestTakerInfoId column
- TestTakerId is working as primary key as well as foreign key in TestTakerInfo Table
- TestTakerID in TestTakerInfo should not be auto generated.
TestTaker |
TestTakerId |
LoginId |
1 |
user-1 |
2 |
user-2 |
|
TestTakerInfo |
TestTakerId |
Name |
1 |
Name1 |
2 |
Name2 |
|
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<testtakerinfo>().HasKey(t => t.TestTakerId);
modelBuilder.Entity<testtakerinfo>().Property(t => t.TestTakerId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<testtakerinfo>()
.HasRequired(t => t.TestTaker)
.WithOptional(t => t.TestTakerInfo);
}
-
How to Specify Junction table for many-to-many relationships in code first? Or
-
How to create many-to-many relationship using entity framework code first?
Requirement: A Test is a set of multiple questions at the same time Question can be applicable for multiple Tests.
solution
- This problem can be solved by establishing many-to-many relationship between Test and Question Table.
- To create many-to-many relationship between two tables we have to introduce junction table.
- In following example TestQuestion table holds many-to-many relationship between Test and Question tables.
- Test 1 has questions 1, 2 and 3
- Test 2 has questions 3 and 4
- Question 3 is applicable in Test 1 and Test2
Test |
TestId |
TestName |
1 |
Test1 |
2 |
Test2 |
3 |
Test3 |
|
TestQuestion |
TestId |
QuestionId |
1 |
1 |
1 |
2 |
1 |
3 |
2 |
3 |
2 |
4 |
|
Question |
QuestionId |
Que |
1 |
Question1 |
2 |
Question2 |
3 |
Question3 |
4 |
Question4 |
|
This relationship can be created in entity framework code first using fluent API in DBContext class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<test>()
.HasMany(t => t.Questions)
.WithMany(t => t.Tests)
.Map(m =>
{
m.ToTable("TestQuestion");
m.MapLeftKey("TestId");
m.MapRightKey("QuestionId");
});
modelBuilder.Conventions.Remove<manytomanycascadedeleteconvention>();
}
-
How to fetch from tables having Many to Many relationship (junction table)
var questions = unitOfWork.QuestionRepository.Get(q => q.Tests.Any(t => t.TestId == testId));
-
How to delete record having many-to-many relationship in Entity Framework?
If deleting record having manay to many relationship is troubling you. try out follwing in OnModelCreating method of DBContext class
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
-
How to add permissions to database so that website should work after deployment on IIS
-
How to resolve error “Login Failed to db, CREATE TABLE permission denied in database”?
Once website is deployed on IIS all request tries to access database using [IIS APPPOOL\ASP.NET v4.0] account. (This can be different in your case depending on version you using). So we need to add this account to database.
- Open SQL Server Management Studio
- Go to Security -- Logins
- Right click on Logins -- New Login -- Search for IIS APPPOOL\ASP.NET v4.0 -- Add
- Expand database -- go to Security -- Users
- Right click on Users -- New User -- Type ‘IISUser’ in user name. (can be anything) -- Search for login name ‘IIS APPPOOL\ASP.NET v4.0’ -- Specify default schema as ‘db_owner’
-
How to resolve if AJAX call not working after deploying on IIS?
Harcoded link path may not work properly after deploying application on IIS. Instead of using hardcoded path use URL helper method as below
url: '@Url.Action("FunctionName", "Controller")'
-
How to resolve session expire / timeout problem?
If there is no interaction with server for long time then it can cause following 2 issues
- Session object gets expired on server
- Authentication cookie file gets expired at client side
Session expire issue need to be handled at three levels as follow:
- Change session timeout in web.config file. (By default it is 20 mins)
<system.web>
<sessionState timeout="300" />
</system.web>
- Open IIS using inetmgr command -- select your website in left pane -- in feature view -- double click ‘session state’ -- in Cookie Settings section Type 300 in Time-out Textbox
- Select Application Pools -- right click on ASP.NET v4.0 (or as per your version) -- Advance Settings -- Set Idle Time-out as 300
Handling Cookie Expiration issue: In web.config file specify timeout in forms tag
<system.web>
<sessionState timeout="300" />
<authentication>
<forms loginUrl="Account/Logon" timeout="300"/>
</authentication>
</system.web>