AngularJs , MVC During the Edit mode why Values not Binding in DropdownList - asp.net-mvc

Im using Mvc with Angularjs here I am fetching data from Database using join and Display data in table when i click on Edit button that particular row is binding in Bootstrap "modal" but why country,State Names not binding in the dropdown.
Here i'm showing Linq query:
public JsonResult GetAssData()
{
var x = (from n in db.Accessors
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new { n.Id, n.Name, n.Email, n.Password, n.GEnder, n.Active, ctr.CountryName, sts.StateName, });
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult EditSer(int id = 0)
{
var x = (from n in db.Accessors
where n.Id == id
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new
{
n.Id,
n.Name,
n.Email,
n.Password,
n.GEnder,
ctr.CountryName,
sts.StateName,
});
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindCtry()
{
var x = from n in db.Countrys select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindStates(int Id = 0)
{
var x = from n in db.States
where n.CountryID == Id
select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
AngularJs
app.controller('MyBindCNtrls', function ($scope, MyBindServiceservice) {
GetAssusData();
function GetAssusData() {
var xxx = MyBindServiceservice.getAss();
xxx.then(function (d) {
$scope.access = d.data;
})
}
$scope.EditEmp = function (Emp) {
alert('in EditModes')
var sss = MyBindServiceservice.EditAssFun(Emp.Id);
sss.then(function (d) {
$scope.Id = Emp.Id;
$scope.Name = Emp.Name;
$scope.GEnder = Emp.GEnder;
$scope.Email = Emp.Email;
$scope.Password = Emp.Password;
$scope.CountryID = Emp.CountryID;
$scope.CountryName = Emp.CountryName;
$scope.StateName = Emp.StateName;
$scope.ValidAction = 'Update';
$('#Modalpopup').modal('show');
})
}
})
app.service('MyBindServiceservice', function ($http) {
this.getAss = function () {
var xx = $http({
url: '/Bindctrl/GetAssData',
method: 'Get',
params: JSON.stringify(),
content: { 'content-type': 'application/Json' }
})
return xx;
}
this.EditAssFun = function (Id) {
alert('enter in edit ser')
var sts = $http({
url: '/Bindctrl/EditSer',
method: 'Get',
params: {
Id: JSON.stringify(Id)
}
});
return sts;
}
});
<div ng-controller="MyBindCNtrls">
<table class="table table-bordered">
<tr>
<th><b>Id</b></th>
<th><b>Name</b></th>
<th><b>Email</b></th>
<th><b>Password</b></th>
<th><b>Gender</b></th>
<th><b>CountryName</b></th>
<th><b>StateName</b></th>
<th><b>Action</b></th>
</tr>
<tr ng-repeat="Accessor in access">
<td>{{Accessor.Id}}</td>
<td>{{Accessor.Name}}</td>
<td>{{Accessor.Email}}</td>
<td>{{Accessor.Password}}</td>
<td>{{Accessor.GEnder}}</td>
<td>{{Accessor.CountryName}}</td>
<td>{{Accessor.StateName}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" value="Edit" ng-click="EditEmp(Accessor)"><span class="glyphicon glyphicon-pencil"></span></button>
</td>
</tr>
</table>
<div class="modal" id="Modalpopup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>{{msg}}Login Details</h3>
</div>
<div class="modal-body">
<form novalidate name="f1" ng-submit="SaveDb(Ass)">
<div>
{{Errormsg}}
</div>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Name
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="nam" ng-model="Name" ng-class="Submittes?'ng-dirty':''" required autofocus />
<span class="Error" ng-show="(f1.nam.$dirty || Submittes) && f1.nam.$error.required">Enter Name</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Email
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="MailId" ng-model="Email" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.MailId.$dirty || Submittes) && f1.MailId.$error.required">Enter Email</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Password" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty || Submittes) && f1.psw.$error.required">Enter Password</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Gender
</div>
<div class="col-sm-8">
<input type="radio" value="Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Male
<input type="radio" value="Fe-Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Fe-Male
<br />
<span class="Error" ng-show="(f1.Gen.$dirty || Submittes) && f1.Gen.$error.required">Select Gender</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Country
</div>
<div class="col-sm-8">
<select class="form-control" name="cntrsy" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-model="CountryID" ng-change="GetStates()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.cntrsy.$dirty || Submittes) && f1.cntrsy.$error.required">Select Country</span>
{{CountryName}}
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
StateName
</div>
<div class="col-sm-8">
<select class="form-control" name="sts" ng-options="I.StateID as I.StateName for I in StateList" ng-model="StateID" ng-change="GetCitys()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.sts.$dirty || Submittes) && f1.sts.$error.required">Select States</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-sm btn-success pull-right" value="{{ValidAction}}" ng-class="SaveAndSubmit()" />
#* <input type="button" class="btn btn-sm pull-right" value="Cancel" id="BtnCancel" />*#
</div>
</form>
</div>
</div>
</div>
</div>
</div>

Related

How to Save records to Master-detail tables in ASP.NET MVC 5

I have Test and Deta(Details) table in DB. With Entity Framework 5 I have obtained a model so I have classes generated from it. I also created controllers and views for the Deta table. I can add, clear and delete the records before saving but finally, I can't to save the records.
Test table has
(TestID,
MissionCode,
StartDate,
EndDate)
Deta table has
(DetaId,
TestType,
TestDate,
Driver,
Place,
TestID)
I used the following script in the view to add, clear and save the record.
#section scripts{
<script>
//Show Modal.
function addNewDeta() {
$("#newDetaModal").modal();
}
//Add Multiple Order.
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#testType").val()) == "" || $.trim($("#testDate").val()) == "" || $.trim($("#driver").val()) == "" || $.trim($("#place").val()) == "") return;
var testType = $("#testType").val(),
testDate = $("#testDate").val(),
driver = $("#driver").val(),
place = $("#place").val(),
detailsTableBody = $("#detailsTable tbody");
var tstItem = '<tr><td>' + testType + '</td><td>' + testDate + '</td><td>' + driver + '</td><td>' + place + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(tstItem);
clearItem();
});
//After Add A New Order In The List, Clear Clean The Form For Add More Order.
function clearItem() {
$("#testType").val('');
$("#testDate").val('');
$("#driver").val('');
$("#place").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove It.
$(document).on('click', 'a.deleteItem', function (e) {
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveDeta(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Detas/SaveDeta",
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveDeta").click(function (e) {
e.preventDefault();
var detaArr = [];
detaArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
detaArr.push({
testType: $(this).find('td:eq(0)').html(),
testDate: $(this).find('td:eq(1)').html(),
driver: $(this).find('td:eq(2)').html(),
place: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
missionCode: $("#missionCode").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
deta: detaArr
});
$.when(saveDeta(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
}
This is the controller
namespace WebApplication2.Controllers
{
public class DetasController : Controller
{
ETHADAMISEntities db = new ETHADAMISEntities();
public ActionResult Index()
{
List<Test> DetaAndTest = db.Tests.ToList();
return View(DetaAndTest);
}
public ActionResult SaveDeta(string missionCode, DateTime startDate, DateTime endDate, Deta[] deta)
{
string result = "Error! Test Detail Is Not Complete!";
if (missionCode != null && startDate != null && endDate != null && deta != null)
{
var tstId = Guid.NewGuid();
Test model = new Test
{
TestID = tstId,
MissionCode = missionCode,
StartDate = startDate,
EndDate = endDate
};
db.Tests.Add(model);
foreach (var item in deta)
{
var id = Guid.NewGuid();
Deta O = new Deta
{
DetaId = id,
TestType = item.TestType,
TestDate = item.TestDate,
Driver = item.Driver,
Place = item.Place,
TestID = tstId
};
db.Detas.Add(O);
}
db.SaveChanges();
result = "Success! Test with Detail Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
This is the view
#model IEnumerable<WebApplication2.Models.Test>
<br /><br />
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<h2 class="panel-title pull-left" style="margin-left:10px;">
<strong>Test Details</strong>
</h2>
<button style="margin-right:10px" class="btn btn-primary pull-right" onclick="addNewDeta()">New Test</button>
</div>
</div>
#*Receive All Database Data From Controller And Display Those Data In Client Side*#
#if (Model.Count() != 0)
{
foreach (var item in Model)
{
<div class="panel-body">
<table class="table table-striped table-responsive">
<tbody>
<tr>
<td>Mission Code : #item.MissionCode </td>
<td>Start Date : #item.StartDate </td>
<td>End Date : #item.EndDate</td>
</tr>
<tr>
<td colspan="3">
<table class="table table-bordered">
<tbody>
<tr>
<th>Test Type</th>
<th>Test Date</th>
<th>Driver</th>
<th>Place</th>
</tr>
#foreach (var deta in item.Detas)
{
<tr>
<td>#deta.TestType</td>
<td>#deta.TestDate</td>
<td>#deta.Driver</td>
<td>#deta.Place</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
}
}
else
{
<div class="panel-body">
<h3 style="color:red;">Empty!</h3>
</div>
}
</div>
#*Desing Bootstrap Modal With Order Form*#
<div class="modal fade" id="newDetaModal">
<div class="modal-dialog modal-lg" style=" width: 900px !important;">
<div class="modal-content">
<div class="modal-header">
×
<h4>Add New Test</h4>
</div>
<form id="NewDetailForm">
<div class="modal-body">
#*Test Details*#
<h5 style="color:#ff6347">Tests</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="TestID" />
<div class="form-group">
<label class="control-label col-md-2">
Mission Code
</label>
<div class="col-md-4">
<input type="text" id="missionCode" name="missionCode" placeholder="Mission Code" class="form-control" />
</div>
<label class="control-label col-md-2">
Start Date
</label>
<div class="col-md-4">
<input type="text" id="startDate" name="startDate" placeholder="Start Date" class="form-control" />
</div>
<label class="control-label col-md-2">
End Date
</label>
<div class="col-md-4">
<input type="text" id="endDate" name="endDate" placeholder="End Date" class="form-control" />
</div>
</div>
</div>
#*Test Detail Details*#
<h5 style="margin-top:10px;color:#ff6347">Test Details</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="DetaId" />
<div class="form-group">
<label class="control-label col-md-2">
Test Type
</label>
<div class="col-md-4">
<input type="text" id="testType" name="testType" placeholder="Test Type" class="form-control" />
</div>
<label class="control-label col-md-2">
Test Date
</label>
<div class="col-md-4">
<input type="datetime" id="testDate" name="testDate" placeholder="Test Date" class="form-control" />
</div>
<label class="control-label col-md-2">
Place
</label>
<div class="col-md-4">
<input type="text" id="place" name="place" placeholder="Place" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">
Driver
</label>
<div class="col-md-4">
<input type="text" id="driver" name="driver" placeholder="Driver" class="form-control" />
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">AddToList</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead>
<tr>
<th style="width:30%">Test Type</th>
<th style="width:20%">Test Date</th>
<th style="width:25%">Driver</th>
<th style="width:15%">Place</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveDeta" type="submit" class="btn btn-success">Save Test Detail</button>
</div>
</form>
</div>
</div>
</div>

Calling a view from different models in ASP.NET MVC

In my ASP.NET MVC application in the view, I'm calling another view that is not related to the current model. There I need some help that how to call the different model views from another view.
#model Asp_PASMVC.Models.VehicleService
#using Asp_PASMVC.Infrastructure
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> CompanyList = (List<SelectListItem>)TempData.Peek("ComapnyList");
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
Asp_PASMVC.Models.AppRequest RequestDetails = (Asp_PASMVC.Models.AppRequest)TempData.Peek("RequestDetails");
}
#{
Html.RenderPartial("_MainRequestView", RequestDetails);
}
#using (Html.BeginForm("WorkshopUpdate", "VehicleService", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.Req_Id)
#Html.AntiForgeryToken()
if (Model != null && Model.VehicleServiceApproveDetails != null)
{
foreach (Asp_PASMVC.Models.VehicleServiceApproveDetails Emp in Model.VehicleServiceApproveDetails)
{
Html.RenderPartial("_WorkshopUpdate", Emp);
}
}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Approver Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div>
<fieldset id="pnlApproverList" style="display:none">
<legend><h5>To whom you want to send this request for approval ? </h5> </legend>
<br />
<ul id="RequApprover" style="list-style-type: none">
#if (Model != null && Model.ApprovalPartyList != null)
{
foreach (Asp_PASMVC.Models.ApprovalParty Emp in Model.ApprovalPartyList)
{
Html.RenderPartial("_ApprovalView", Emp);
}
}
</ul>
<button type="button" id="addAnotherApprover" class="btn btn-success" href="#" onclick="this.style.display = 'none';">Add</button>
<script type="text/javascript">
$(function () {
// $("#movieEditor").sortable();
$("#addAnotherApprover").click(function () {
$.get('/VehicleService/AddApproverToReq', function (template) {
$("#RequApprover").append(template);
});
});
});
</script>
<br />
</fieldset>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update and Sent" class="btn btn-success" />
</div>
</div>
</div>
}
<p>
#Html.ActionLink("Back to List", "Index")
</p>
So likewise here the model is VehicleService. So within that view, I want to call another view that is not within the vehicleservice model.
But I cannot load that partial view within this view. Is there any way to do this?
#model Asp_PASMVC.Models.ApprovalParty
#using Asp_PASMVC.Infrastructure
#{
string UserLvel = TempData.Peek("UserLevelClaims").ToString();
}
<li style="padding-bottom:15px">
#using (Html.BeginCollectionItem("ApprovalPartyList"))
{
<div class="row">
<div class="col-md-5 col-sm-5">
<div class="form-group">
<label>
#Html.RadioButtonFor(m => m.Approve_Type, false)
<span class="radiomargin">For Manager</span>
</label>
<br />
#if (UserLvel != "1")
{
<label>
#Html.RadioButtonFor(m => m.Approve_Type, true)
<span class="radiomargin">For Top Manager </span>
</label>
#Html.ValidationMessageFor(model => model.Approve_Type, "", new { #class = "text-danger" })
}
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
Select the Approver
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { #id = "ddlEmployees", #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Approver_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
</li>
Create a ViewModel which can have both Properties and pass that viewmodel to View
Model class:
public class VehicleSerivceViewModel
{
public VehicleService VehicleService { get; set; }
public ApprovalParty ApprovalParty { get; set; }
}
In View :
#model Asp_PASMVC.Models.VehicleServiceVewModel
pass ViewModel to partial as below:
#Model.ApprovalParty

Get request from RazorPage with ViewComponent

I tray use ViewComponent in Razor Page with condition,
and each Viewcomponents are separate,
My razorpage is "/Subfolder/Index.cshtml"
<div class="row">
<div class="col-md-4">
#await Component.InvokeAsync("RightMenu")
</div>
<div class="col-md-8">
#if (Model.SIndex != 0)
{
#await Component.InvokeAsync("SubContent", new { id = Model.SIndex })
}
#if (Model.SIndex == 15)
{
<div class="row">
<div class="col-md-12">
<form method="post">
#await Component.InvokeAsync("QuestionUs", new { askLibrarian = new Lib.Model.AskLibrarian() })
<div class="form-group">
<input type="submit" value="ask Question" class="btn btn-default" asp-page-handler="question" />
</div>
</form>
</div>
</div>
}
</div>
and code behind of this is "/subfolder/index.cshtml.cs"
public class IndexModel : PageModel
{
private readonly Lib.Model.LibContext _context;
[BindProperty]
public int SIndex { get; set; }
public async Task OnGet(int Id)
{
SIndex = Id;
}
[BindProperty]
public AskLibrarian AskLibrarian { get; set; }
public async Task<IActionResult> OnPostquestionAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.AskLibrarians.Add(AskLibrarian);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
Now "questionViewcomponent" is a simple form that show many input elements
in "/subfolder/component/questionus/default.cshtml"
#model Lib.Model.AskLibrarian
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-md-6">
<label asp-for="FullName" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user"></i></div>
</div>
<input asp-for="FullName" class="form-control" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="form-group col-md-6">
<label asp-for="Email" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-envelope"></i></div>
</div>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label asp-for="LibraryNameId" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-book"></i></div>
</div>
<select asp-for="LibraryNameId" class="form-control" asp-items="ViewBag.LibraryNameId"></select>
</div>
</div>
<div class="form-group col-md-8">
<label asp-for="Subject" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-book-reader"></i></div>
</div>
<input asp-for="Subject" class="form-control" />
<span asp-validation-for="Subject" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Text" class="control-label"></label>
<textarea asp-for="Text" class="form-control" style="min-height:250px;"></textarea>
<span asp-validation-for="Text" class="text-danger"></span>
</div>
set breakpoint on "OnpostQuestionAsync", When I click on submit button with "question" handler do nothing and show me a blank page instead question form.
how can I resolve That
After a long Time my problem resolved by remove
<input type="submit" value="ask Question" class="btn btn-default" asp-page-handler="question" />
and add in form tag
<form method="post" sp-page-handler="question">

Not hitting controller in MVC

In my submit of my login form which is in pop-up it is not hitting the controller even though I provided the code in beginform with post method. I need to send the username and password to my controller for verification. Unable to figure out why it is not hitting.
[HttpPost]
public ActionResult LoginUser(UserInfo objUser)
{
int res = udaObj.CheckUser(objUser.UserName, objUser.Password);
if (res >= 1)
{
return RedirectToAction("Appointment", "Home");
}
else
{
//For testing purpose
return RedirectToAction("Appointment", "Home");
}
}
My view is as follows:
#using (Html.BeginForm("LoginUser", "Home", FormMethod.Post, new { id = "loginForm" }))
{
<div class="tab-pane fade active in" id="signin">
<fieldset>
<!-- Sign In Form -->
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="userid">Alias:</label>
<div class="controls">
#* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*#
#Html.TextBoxFor(x => x.UserName, new { #class = "form-control input-large", #placeholder = "Joek#irawath.com", #required = "" , #id="userid" })
</div>
</div>
<!-- Password input-->
<div class="control-group">
<label class="control-label" for="passwordinput">Password:</label>
<div class="controls">
#*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*#
#Html.TextBoxFor(x => x.Password, new { #class = "form-control input-large", #placeholder = "********", #required = "", #type = "password" , #id="passwordinput" })
</div>
</div>
<!-- Multiple Checkboxes (inline) -->
<div class="control-group">
<label class="control-label" for="rememberme"></label>
<div class="controls">
<label class="checkbox inline" for="rememberme-0">
<input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
Remember me
</label>
</div>
</div>
<button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="signin"></label>
<div class="controls">
#* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*#
</div>
</div>
</fieldset>
</div>
}
Check if the object UserInfo is the same model you are using in your view. Try using a FormCollection instead and check.

MVC Razor Dropdownlist value get reset when clicking on WebGrid paging

I've been stuck almost two days now and still couldn't find a solution.
I have a WebGrid in a partial view, and I'm loading it inside the main view which has 4 search fields.
I'm using Request.IsAjaxRequest() to identify which view has to be loaded.
If it's an Ajax call I return the Partial View else the Main View. If I return the "Main View" the Dropdownlist value get reset as it refresh. I want to keep the Dropdownlist value selected by the user after the results has been loaded.
Here's my Main View,
<div class="row">
#if (Model != null)
{
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by State", new { #class = "form-font-size label-margin-top" })
#Html.DropDownList("stateList", (SelectList)ViewBag.StatesList, "ALL", new { #class = "form-control", #id = "ddlState" })
#*<select class="form-control" id="ddlState">
<option value="0">ALL</option>(SelectList)ViewBag.StatesList
<option value="1">NT</option>
<option value="2">WA</option>
<option value="3">QLD</option>
</select>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Job Id", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.JobId" id="txtName" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Client", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.Client" id="txtClientName" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtClientName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Location", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.Location" id="txtLocation" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtClientName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-xs-12 col-sm-8 increase-bottom-padding">
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>All Jobs
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>My Jobs
</div>
<div id="grid">
#Html.Partial("_JobInstructionWebGridPartial")
</div>
}
else
{
<div class="col-xs-12 col-sm-8 increase-bottom-padding-job remove-left-right-padding">
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>All Jobs
</div>
#:<div class="col-md-12 alert alert-danger"><strong>You don't have any jobs, If you want to search any Job please click on "'All Jobs'" ..</strong></div>
}
</div>
Here's my Partial View
#model IEnumerable<SurveyManagement.Models.Job.ViewModel_JobInstruction_WebGrid>
#{
if (Model != null)
{
var grid = new WebGrid(source: Model, canPage: true, canSort: false, rowsPerPage: 10, ajaxUpdateContainerId: "jobgridcontent");
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="table-responsive">
<div class="table" id="tbljobbook">
#grid.GetHtml(tableStyle: "table table-striped table-bordered table-hover",
headerStyle: "jobinstruction-webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns:
grid.Columns(
grid.Column("JobId", header: "Job Id", style: "jobinstruction-row-style col-md-1", format: #<text><label class="lblJobId">#item.JobId</label> </text>),
grid.Column("ClientName", header: "Client Name", style: "col-md-2 job-webgrid-column-max-width uppercase"),
grid.Column("JobLocation", header: "Job Location", style: "col-md-2 job-webgrid-column-max-width"),
grid.Column("JobDescription", header: "Job Description", style: "col-md-2 job-webgrid-column-max-width"),
grid.Column("JobStatus", header: "Job Status", style: "jobinstruction-row-style col-md-1 uppercase"),
grid.Column("Action", format: #<text>
<button type="button" class="edit-user btn btn-info btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Edit Job"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-swr btn btn-tumblr btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="SWR List"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-swr-new btn btn-facebook btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="New SWR"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-view btn btn-primary btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Field Entry List"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-create btn btn-warning btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="New Field Entry"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-admin btn btn-danger btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Admin"><i class="fa fa-list"></i></button></text>, style: "col-md-4 jobinstruction-row-style", canSort: false)
))
</div>
</div>
</div>
}
Calling the Controller Action on Dropdownlist change event,
$(document).ready(function () {
$('#ddlState').change(function () {
$.ajax({
type: "GET",
url: '#Url.Action("SearchJobDetails")',
data: { jobId: $('#txtName').val(), client: $('#txtClientName').val(), location: $('#txtLocation').val(), state: $("#ddlState option:selected").text() },
success: function (data) {
$('#grid').html(data);
}
});
});
});
Here is my Controller Action,
public ActionResult SearchJobDetails(string jobId = null, string client = null, string location = null, string state = null)
{
try
{
ViewBag.IsRecordsSave = false;
ViewBag.sectionid = 1;
ViewBag.Location = location;
ViewBag.Client = client;
ViewBag.JobId = jobId;
List<States> StateList = Enum.GetValues(typeof(States)).Cast<States>().ToList();
ViewBag.StatesList = new SelectList(StateList);
ViewBag.SelectedState = state;
if (Request.IsAjaxRequest())
{
return PartialView("_JobInstructionWebGridPartial", GetJobDetails(jobId, client, 0, location, state));
}
else
{
return View("JobInstructionsDetails", GetJobDetails(jobId, client, 0, location, state));
}
}
}
As you can see in the above controller, ViewBag.StatesList is where I assign the States in my Enum. If I return the View (else part), the dropdownlist value get reset. I managed to keep the input text box values by putting value="#ViewBag.Location" so it set the values back from ViewBag. How do I do that for the Dropdownlist? Please help.
You need to use Html.DropdownlistFor Just modify the code as shown in the example below.where m.jobID is the selected value. To keep the value after postback its wise to use Model always.
#Html.DropDownListFor(m => m.jobID, new SelectList(Model.Clients, "ID", "ClientName"),new { #class = "form-control" })

Resources