There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'SupervisingPhysician' - asp.net-mvc-5

In PatientViewModel
public IEnumerable<SelectListItem> SupervisingPhysician { get; set; }
In PatientController
// Supervising Physicians
List<SelectListItem> listSelectSPListItems = new List<SelectListItem>();
foreach (Physician physician in db.Physicians.Where(p => p.IsSupervising == true))
{
SelectListItem selectSPList = new SelectListItem()
{
Text = physician.FirstName +" "+ physician.LastName,
Value = physician.Id.ToString()
};
listSelectSPListItems.Add(selectSPList);
}
ViewBag.SupervisingPhysicians = new SelectList(listSelectSPListItems,"Value","Text");
In View
#Html.DropDownListFor(x => x.SupervisingPhysician, (SelectList)ViewBag.SupervisingPhysicians, htmlAttributes: new { #class = "form-control col-md-4" })
Error:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'SupervisingPhysician'.

Related

Complete drop down list when editing whit a Joining the table in Asp.net MVC 5

I have three tables in the name of Person and City and Evidence whose table has person a few columns including FirstName , LastName ,cityid (cityID), EvidenceID that id of the table (EvidenceID), the EvidenceID fields and the cityID are foreign keys, and to the id table City maps, Evidence connected
Now I want to have two combo boxes (tag) when I'm creating a new person, so that they can list them in place of the ID of the city and the id of the Evidence , and list them in the cowboy box.
Also, when editing, I want to know that when I go to the editing form, you can see the name of the city and the person's profile on the cowboys, and we can also see and edit the other cobblestones.
please guide me.
[HttpGet]
public ActionResult EditPerson(int id)
{
var q = (from a in db.Person
where a.ID.Equals(id)
select a).SingleOrDefault();
if (q != null)
{
return View(q);
}
else
{
return RedirectToAction("ShowPerson", "Home");
}
}
[HttpPost]
public ActionResult EditPerson(Person per)
{
var q = (from a in db.Person
where a.ID.Equals(per.ID)
select a).SingleOrDefault();
q.FirstName = per.FirstName;
q.LastName = per.LastName;
q.UserName = per.UserName;
q.EvidenceID = per.EvidenceID;
q.Mobile = per.Mobile;
q.Stutus = false;
q.CodeMelli = per.CodeMelli;
q.CityID = per.CityID;
q.Address = per.Address;
q.Access = per.Access;
q.Email = per.Email;
q.Image = per.Image;
db.Person.Attach(q);
db.Entry(q).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("ShowPerson", "Home");
}
[HttpGet]
public ActionResult CreatePerson()
{
return View();
}
[HttpPost]
public ActionResult CreatePerson(Person per)
{
Person p = new Person();
p.FirstName = per.FirstName;
p.LastName = per.LastName;
p.UserName = per.UserName;
p.EvidenceID = per.EvidenceID;
p.Mobile = per.Mobile;
p.Stutus = false;
p.CodeMelli = per.CodeMelli;
p.CityID = per.CityID;
p.Address = per.Address;
p.Access = per.Access;
p.Email = per.Email;
p.Image = per.Image;
db.Person.Add(p);
db.SaveChanges();
return RedirectToAction("ShowPerson", "Home");
}
code in view edit :
<div class="form-group">
#Html.LabelFor(model => model.CityID, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CityID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CityID, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.EvidenceID, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.EvidenceID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EvidenceID, "", new { #class = "text-danger" })
Your question is not being understood but what you need is a dropdownlist from three different models as i'm guessing...
try this in your own domain:
var dataForDL = _db.ModelName.Select(a => new
{
Text = a.PersonName +" "+ a.Evidence.Name +" "+ a.City.CityName,
Value = a.Id
}).ToList();
ViewBag.DropdownListForModel = new SelectList(dataForDL, "Value", "Text");
In the view.cshtml
#Html.DropDownList("DropdownListForModel", null, "-- Please Select Something --", htmlAttributes: new { #class = "form-control" })

Microsoft Azure > Azure Active Directory

I created an extension :
SchemaExtension objExtDef = new SchemaExtension()
{
Description = "Extention to Store User Dates",
Id = "UserDates",
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty() { Name = "CreateDate", Type = "DateTime" },
new ExtensionSchemaProperty() { Name = "PasswordChangeDate", Type = "DateTime" }
},
TargetTypes = new List<string>()
{
"User"
}
};
SchemaExtension schemaExtension = Task.Run(() => graphserviceClient.SchemaExtensions.Request().AddAsync(objExtDef)).Result;
Made it Available :
var schemaExtension = new SchemaExtension
{
Status = "Available",
};
var result = Task.Run(() => graphserviceClient.SchemaExtensions["extuce7u7qp_UserDates"].Request().UpdateAsync(schemaExtension)).Result;
Searched and confirmed that it is created and available :
var lstAllExtensions = Task.Run(() => graphserviceClient.SchemaExtensions.Request().Filter("id%20eq%20'extuce7u7qp_UserDates'").GetAsync()).Result;
Trying to add user along with additional data in that extension :
UserDatesExtension objUserDatesExtension = new UserDatesExtension();
objUserDatesExtension.CreateDate = DateTime.Today;
objUserDatesExtension.PasswordChangeDate = DateTime.Today;
dctExtensions.Add("extuce7u7qp_UserDates", objUserDatesExtension);
Microsoft.Graph.User objNewUser = new Microsoft.Graph.User
{
AccountEnabled = true,
DisplayName = string.Format("{0} {1}", objUser.FirstName, objUser.LastName),
MailNickname = "TestUC",
PasswordProfile = new PasswordProfile
{
Password = "testpass",
ForceChangePasswordNextSignIn = false
},
UserPrincipalName = string.Format("{0}#test.onmicrosoft.com", objUser.UserIdentity),
GivenName = objUser.FirstName,
Surname = objUser.LastName,
City = objUser.Address != null ? objUser.Address.City : null,
Country = objUser.Address != null ? objUser.Address.Country : null,
State = objUser.Address != null ? objUser.Address.Region : null,
MobilePhone = !string.IsNullOrEmpty(objUser.Phone) ? objUser.Phone : null,
PreferredLanguage = objUser.PreferredLanguage,
AdditionalData = dctExtensions
};
Microsoft.Graph.User objCreatedUser = Task.Run(() => graphserviceClient.Users.Request().AddAsync(objNewUser)).Result;
That is throwing exception that the extension ID is not valid.
This was working earlier.
UserDatesExtension Class, used above :
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class UserDatesExtension
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "CreateDate", Required = Newtonsoft.Json.Required.Default)]
public DateTime CreateDate { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "PasswordChangeDate", Required = Newtonsoft.Json.Required.Default)]
public DateTime PasswordChangeDate { get; set; }
}

Custom validation are not executing on focus change of applied control but works well in case of form submit

I am using normal mvc textboxfor on strong view, I have created custom validation attribute (the detailed code explained below).
On form submit everything works fine. In case if validation fails by natural it shows error message as configured.
Now when I enter the correct value inside text box I expect the error message to be vanished automatically but this does not happen until I post the form
JS File
$.validator.addMethod('validaterequiredif', function (value, element, parameters) {
var id = parameters['dependentproperty'];
var clickValue = $("input[name=" + id + "]:checked").val();
// get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
if (clickValue == targetvalue) {
if (value == null) {
return false;
}
else {
return $.validator.methods.required.call(
this, value, element, parameters);
}
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.add(
'validaterequiredif',
['dependentproperty', 'targetvalue'],
function (options) {
options.rules['validaterequiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['validaterequiredif'] = options.message;
});
Server side custom validator class as below
public class ValidateRequiredIf : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public ValidateRequiredIf(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
//if (!_innerAttribute.IsValid(value))
if (value == null)
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "validaterequiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
}
Model property
[ValidateRequiredIf("IsFeederSelected", "True", ErrorMessage = "Please select atleast one feeder")]
public List<string> selectedMeterName { get; set; }
Strongly typed view
<div class="meterTextboxRadio col-md-4">
<p>
#Html.RadioButtonFor(m => m.IsFeederSelected, true, new { #class = "radio", #Name = "IsFeederSelected", value = "meter", id = "rdbMeterConsumption", #checked = "checked" })
<span> Feeder</span>
#Html.RadioButtonFor(m => m.IsFeederSelected, false, new { #class = "radio", #Name = "IsFeederSelected", value = "group", id = "rdbGroupConsumption",style= "margin-left: 30px;" })
<span> Group</span>
</p>
<div class="group dropdownhidden" id="MeterNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedMeterName, Model.MeterName
, new { #class = "chosen-select" ,#id= "ddlConsumptionMeterName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Feeders.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
<div class="group dropdownhidden" id="GroupNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedGroupName, Model.GroupName
, new { #class = "chosen-select", #id = "ddlConsumptionGroupName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Group.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
#Html.ValidationMessageFor(m => m.selectedMeterName, "", new { #class = "error" })
#Html.ValidationMessageFor(m => m.selectedGroupName, "", new { #class = "error" })
</div>
Please provide some inputs for the same
Thanks.

Drop down List from Viewbag not following selected property

I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.
List<SelectListItem> year = new List<SelectListItem>();
for (var i = 1990; i <= DateTime.Now.Year; i++)
{
year.Add(new SelectListItem
{
Text = i.ToString(),
Value = i.ToString()
});
}
ViewBag.Year = year;
And in my view:
#Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { #class = "form-control", style = "width: 80px" })
Nothing happens.
Try
#Html.DropDownListFor(model => model.Year, new SelectList(#ViewBag.Year, "Value", "Text", Model.Birthday.Year), new { #class = "form-control", style = "width: 80px" })
It will work as expected.
I used script instead
$('#Year option')
.removeAttr('selected')
.filter('[value=#Model.Birthday.Year]')
.attr('selected', true)

Model is getting null on post on Child Partial View MVC5

I asked this question in a another thread but i never got the answer. Hope someone bright can help me with this.
Basically what i'm trying is to get TestModel back to ActionResult Questions(TestModel test, FormCollection formCollection). Whenever next button is pressed in _Question.cshtml partial View ActionResult Index(TestModel test) is bounded with empty model therefore i can't get anything from user to fill my testModel. Please Help
///////////////Models//////////////
[Serializable]
public class TestModel
{
private QuestionModel _currenQuestionModel;
public int TestID { get; set; }
public string TestName { get; set; }
public string Instructions { get; set; }
public double TestTime { get; set; }
public QuestionModel CurrenQuestionModel
{
get
{
if (_currenQuestionModel == null &&
Questions != null &&
Questions.Count > 0)
_currenQuestionModel = Questions.First();
return _currenQuestionModel;
}
set { _currenQuestionModel = value; }
}
public List<QuestionModel> Questions { get; set; }
}
public class QuestionModel
{
public int QuestionID { get; set; }
public string Question { get; set; }
public bool HasMultipleAnswers { get; set; }
public IList<PossibleAnswerModel> PossibleAnswers { get; set; }
}
public class PossibleAnswerModel
{
public bool IsSelected { get; set; }
public string DisplayText { get; set; }
}
}
////////////////// Controller /////////////////
public class TestController : Controller
{
public ActionResult Index(int id)
{
var model = _testColletion.FirstOrDefault(r => r.TestID == id);
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel test)
{
//var model = (TestModel) Session["CurrentTest"];
return View(test);
}
[ChildActionOnly]
[HttpGet]
public ActionResult Questions(TestModel test)
{
var testModel = _testColletion.Single(r => r.TestID == test.TestID);
return PartialView("_Start", testModel);
}
[HttpPost]
public ActionResult Questions(TestModel test, FormCollection formCollection)
{
var q = formCollection.Count >2 ? formCollection.GetValues(1):null;
var testModel = _testColletion.FirstOrDefault(r => r.TestID == test.TestID);
//if (questionID == 0)
//{
// testModel.CurrenQuestionModel = testModel.Questions.First();
//}
if (!string.IsNullOrWhiteSpace(Request["next"]))
{
var nextQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) + 1;
testModel.CurrenQuestionModel = testModel.Questions[nextQuestionIndex];
}
else if (!string.IsNullOrWhiteSpace(Request["prev"]))
{
var prevQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) - 1;
testModel.CurrenQuestionModel = testModel.Questions[prevQuestionIndex];
}
return PartialView("_Question", testModel);
}
private static List<TestModel> _testColletion = new List<TestModel>()
{
new TestModel()
{
TestID = 1,
TestName = "ASP.NET",
Instructions = "Please choose from appropriate options",
TestTime = 2.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"}
}
},
new TestModel()
{
TestID = 2,
TestName = "ASP.NET MVC",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, HasMultipleAnswers=true, Question = "Question 1", PossibleAnswers = new List<PossibleAnswerModel>()
{
new PossibleAnswerModel(){DisplayText = "Possible Answer 1"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 2"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 3"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 4"},
}},
new QuestionModel(){QuestionID = 2, HasMultipleAnswers=true, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, HasMultipleAnswers=true, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, HasMultipleAnswers=true, Question = "Question 4"},
new QuestionModel(){QuestionID = 5, HasMultipleAnswers=true, Question = "Question 5"},
}
},
new TestModel()
{
TestID = 3,
TestName = "ASP.NET Spring",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, Question = "Question 4"},
}
},
new TestModel()
{
TestID = 4,
TestName = ".NET C#",
Instructions = "Please choose from appropriate options",
TestTime = 4.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"}
}
}
};
}
/////////// Inside _Question.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#*#Html.HiddenFor(r => r.CurrentQuestionID)*#
<div>
<br />
<h4>Question #Model.CurrenQuestionModel.QuestionID</h4>
<hr />
<p>#Model.CurrenQuestionModel.Question</p>
</div>
<p>
#if (Model.CurrenQuestionModel.HasMultipleAnswers)
{
#Html.Partial("_MultipleAnswerQuestionView", Model.CurrenQuestionModel)
}
</p>
<p>
#if (Model.CurrenQuestionModel.QuestionID > 0 && Model.CurrenQuestionModel.QuestionID < Model.Questions.Count)
{
if (Model.CurrenQuestionModel.QuestionID > 1)
{
<input type="submit" class="btn btn-default" value="Previous" name="prev" />
}
<input type="submit" class="btn btn-default" value="Next" name="next" />
}
#if (Model.CurrenQuestionModel.QuestionID == Model.Questions.Count)
{
<input type="submit" class="btn btn-default" value="Finish" name="finish" />
}
</p>
}
//////////// Inside _MultipleAnswerQuestionView.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#if (!Model.CurrenQuestionModel.HasMultipleAnswers)
{
throw new InvalidOperationException("This answer optioin template doesn't support this type of questions");
}
#for (var i = 0; i < Model.CurrenQuestionModel.PossibleAnswers.Count; i++)
{
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<span class="input-group-addon">
#Html.CheckBoxFor(r => r.CurrenQuestionModel.PossibleAnswers[i].IsSelected)
#*<input type="checkbox" value="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected" name="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected">*#
</span>
<p>
#Model.CurrenQuestionModel.PossibleAnswers[i].DisplayText
</p>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
}

Resources