MVC 4 DropDownListFor Set Selected Item Based on Text - c#-4.0

Normally when I use the DropDownListFor helper I'm selecting which item is selected based on an ID (int), but now I have a situation where I need to display which item is selected based on the text (string) and not an ID. In the controller the model is being set correctly to the value that I want with this property:
model.Title
An example title would be "Front Office". I have the following code in my Controller:
ViewBag.Titles = new SelectList(jobTitles, "Name", "Name");
and on the view I have this:
#Html.DropDownListFor(model => model.Title, ViewBag.Titles as SelectList)
The DropDownList is populating correctly with all the expected job titles, it just isn't selecting the correct job title based on model.Title. What am I doing wrong?
UPDATE:
There seems to be something else potentially going wrong in my code, so I'm putting all of it here to see if I'm doing something wrong.
Controller:
public ActionResult Edit(int id = 0)
{
StaffMember staffmember = StaffMember.SelectByID(id); // gets staff member from db
ViewBag.Titles = new SelectList(JobTitle.SelectAll(), "Name", "Name", staffmember.Title); // JobTitle.SelectAll() returns List<JobTitle>
StaffEditModel model = new StaffEditModel();
model.ID = staffmember.ID;
model.ClientID = staffmember.ClientID;
model.FirstName = staffmember.FirstName;
model.MiddleInitial = staffmember.MiddleInitial;
model.LastName = staffmember.LastName;
model.Title = staffmember.Title;
model.Phone = staffmember.Phone;
model.Email = staffmember.Email;
model.Birthday = staffmember.Birthday;
model.HireDate = staffmember.HireDate;
model.Biography = staffmember.Biography;
if (staffmember == null)
{
return HttpNotFound();
}
return View(model);
}
Model:
public class StaffEditModel
{
public int ID { get; set; }
public int ClientID { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Middle Initial")]
public string MiddleInitial { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string Title { get; set; } // this is the property I'm trying to show in DropDown
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public string Birthday { get; set; }
[Display(Name = "Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public string HireDate { get; set; }
public string Email { get; set; }
[MaxLength(14)]
public string Phone { get; set; }
public string Biography { get; set; }
}
View:
#Html.DropDownListFor(model => model.Title, new SelectList(ViewBag.Titles,"Value","Text", Model.Title))

This should work.
You can pass ViewBag.Titles as List<SelectListItem> from controller
var jobList = new List<SelectListItem>();
foreach (var job in jobTitles)
{
var item = new SelectListItem();
item.Value = job.PropertyName; //the property you want to display i.e. Title
item.Text = job.PropertyName;
jobList.Add(item);
}
ViewBag.Title = jobList;
and then in the view,
#Html.DropDownListFor(model => model.Title, new SelectList(ViewBag.Titles,"Value","Text", Model.Title))

I know I'm late to the party on this, but I had a similar problem and thought I would add what I've found.
I haven't figured out the why yet - I'm still researching (that's how I ended up here) - but I think it has something to do with the fact that you're using the word Title
I've got the exact same scenario and as soon as I changed my model to CustomerTitle instead of Title things worked as expected.
Initial thoughts are that the model binder is finding Title somewhere else in the DOM and getting tripped up. Complete speculation. If I have more time I'll keep digging for the why

Related

How to upload an attachment to a list item using Microsoft.SharePoint.Client?

I am trying to create a new list item with an attachment. Bellow is my code:
using (var clientContext = new ClientContext(_sharepointSite))
{
clientContext.Credentials = _credentials;
var list = clientContext.Web.Lists.GetByTitle("ListName");
var listEntry = list.AddItem(new ListItemCreationInformation());
listEntry["Title"] = model.Title;
listEntry.Update();
clientContext.ExecuteQuery();
var attInfo = new AttachmentCreationInformation();
attInfo.ContentStream = model.File.InputStream;
attInfo.FileName = model.File.FileName;
var attachment = listEntry.AttachmentFiles.Add(attInfo);
clientContext.Load(attachment);
clientContext.ExecuteQuery();
}
The list item creation code works fine but the file attachment code throws the following error:
Microsoft.SharePoint.Client.ServerException: Data at the root level is invalid. Line 2, position 1.
on the last clientContext.ExecuteQuery(). Does anyone have any ideas as to what the cause of this is?
UPDATE:
Here is my schema for the model:
public class UploadFileModel : IValidatableObject
{
[Required, MaxLength(100), Display(Name = "File title")]
public string Title { get; set; }
[Required, Display(Name = "User type")]
public UserTypes? UserType { get; set; }
[MaxLength(100), Display(Name = "Health care organization name")]
public string HealthCareOrgName { get; set; }
[MaxLength(100), Display(Name = "User's email")]
public string UserEmail { get; set; }
[Required]
public HttpPostedFileBase File { get; set; }
}
Basically the File property is just the file the user is trying to upload...

Azure, DocumentDB cannot save POCO object as a document

I have serious problem with MS Azure DocumentDB.
I Know it's in pre-realese only, but as I know it is said that it is possible to save Dynamic and POCO objects as a documents. When I save dynamic object it works just fine (object is added to a collection):
dynamic dynamicObject = new
{
testId = "12",
text = "aaa bbb ccc"
};
await client.CreateDocumentAsync(collectionSelfLink, dynamicObject);
However, when I try to add a POCO obejct, it doesnt works (nothing is added to a collection):
public class House
{
[JsonProperty(PropertyName = "id")]
public string HouseId { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "address")]
public string Address { get; set; }
}
------------------
House house = new House() {HouseId = "1", Name="TestHouse", Address="asdasdasd"};
await client.CreateDocumentAsync(collectionSelfLink, house);
Everything else is the same.
EDIT: temp solution is to inherit your POCO class from Microsoft.Azure.Documents.Document class.
as per my comment, can't repro this.
here is my test project:
static void Main(string[] args)
{
House house = new House() { HouseId = "1", Name = "TestHouse", Address = "asdasdasd" };
Document doc = client.CreateDocumentAsync(col.DocumentsLink, house).Result;
Console.Write(doc.SelfLink);
Console.ReadLine();
}
public class House
{
[JsonProperty(PropertyName = "id")]
public string HouseId { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "address")]
public string Address { get; set; }
}
results in 1 document created and doc.selfLink being printed to the Console.

Save changes in database controller class asp.net mvc5 identity

Visual Studio 2013, ASP.NEt MVC 5 Identity
Please someone help me in how to save the information in the database through controller. Let me explain...I want the following to happen:
The user when logged is able update his Education information. After making changes in the fields, he will press the save button and the information is saved in the database. This works fine when i am doing so with the default aspnet users class, i take the usermanager. update method and the info is saved, but i am unable to do so with for any other table. I would be really thankful if someone helps me.
Here's the controller class edit method
public async Task<ActionResult> Edit(string id, Education education)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login");
}
var db = new ApplicationDbContext();
var educationdb = db.Edu.First(u => u.EducationID == education.EducationID);
educationdb.Qualification = education.Qualification;
educationdb.School = education.School;
educationdb.SchFrom = education.SchFrom;
educationdb.SchTo = education.SchTo;
educationdb.College = education.College;
educationdb.ClgFrom = education.ClgFrom;
educationdb.ClgTo = education.ClgTo;
educationdb.University = education.University;
educationdb.UniFrom = education.UniTo;
educationdb.Description = education.Description;
db.Entry(educationdb).State = System.Data.Entity.EntityState.Modified;
await db.SaveChangesAsync();
//return RedirectToAction("Index");
return View();
}
this is the model class:
namespace theme1.Models
{
public class Education
{
public string EducationID { get; set; }
public string UserID { get; set; }
public ApplicationUser User { get; set; }
public string Qualification { get; set; }
public string School { get; set; }
[DataType(DataType.Date)]
public DateTime SchFrom { get; set; }
[DataType(DataType.Date)]
public DateTime SchTo { get; set; }
public string College { get; set; }
[DataType(DataType.Date)]
public DateTime ClgFrom { get; set; }
[DataType(DataType.Date)]
public DateTime ClgTo { get; set; }
public string University { get; set; }
[DataType(DataType.Date)]
public DateTime UniFrom { get; set; }
[DataType(DataType.Date)]
public DateTime UniTo { get; set; }
public string Description { get; set; }
}
}
var educationdb = db.Edu.First(u => u.EducationID == education.EducationID); this line gives me an error Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:
Line 109: var educationdb = db.Edu.First(u => u.EducationID == education.EducationID);
Instead of :
var educationdb = db.Edu.First(u => u.EducationID == education.EducationID);
Try this :
var educationdb = db.Edu.Where(u => u.EducationID == education.EducationID).FirstOrDefault();
OR
Instead of :
var educationdb = db.Edu.First(u => u.EducationID == education.EducationID);
Try this :
var educationdb = db.Edu.FirstOrDefault(u => u.EducationID == education.EducationID);
I suspect that your missing the DBSet for Education model in ApplicationContext.
If this doesn't fix it, could you please provide the code for your ApplicationContext class?
I cant comment on your discussion with Kartikeya since I am new to stackoverflow and lack reputation.
But after you changed your lambda:
var educationdb = db.Edu.Where(u => u.EducationID ==
education.EducationID).FirstOrDefault();
From your discussion with Kartikeya It sounds like you are thinking of Creating rather than editing. You cant edit something that doesn´t exist.
// GET: Model
public ActionResult Create()
{
return View();
}
in MVC 5 it is very easy to scaffold the view by right clicking inside that Action and chosing "add view" and insert the information you need, and when you have created the view, create your post method for Create:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include ="EducationID, UserId....")] Education education)
{
if (ModelState.IsValid)
{
//any extra logic you might want
db.Edu.Add(education);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(education);
}

Entity Framework Codefirst approach

Am Using EntityFramework codefirst approach.my coding is
class Blog
{
[Key]
public int BlobId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
class Post
{
[Key]
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlobId { get; set; }
public virtual Blog Blob { get; set; }
}
class BlogContext:DbContext
{
public BlogContext() : base("constr") { }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new BlogContext())
{
Console.WriteLine("Enter a name for a new blob:");
var name = Console.ReadLine();
var b = new Blog { Name = name };
db.Blogs.Add(b);
db.SaveChanges();
Till this step i created two tables(Blogs and Posts)in my SQlserver.The BlobId is primary key in Blogs table.and foreign key in Posts table.and Blogid in blog table is auto incremented.postid in posts table is also auto incremented
class Program
{
static void Main(string[] args)
{
using (var db = new BlogContext())
{
Console.WriteLine("Enter a name for a new blob:");
var name = Console.ReadLine();
var b = new Blog { Name = name };
db.Blogs.Add(b);
db.SaveChanges();
Here i added name in the blogtable
var id1 = from val in db.Blogs
where val.Name == name
select val.BlobId;
Now by using Name am obtaining the blogid of blogs table
Console.WriteLine("Enter Title:");
var title = Console.ReadLine();
Console.WriteLine("Enter Content");
var content = Console.ReadLine();
var c = new Post { Title = title, Content = content, BlobId = id1};
db.Posts.Add(c);
db.SaveChanges();
here am reading the data for title,content.Then adding the title,content and blogid(which i obtained from another table) into Posts table
I getting error at BlobId = id1
Am getting Cannot implicitly convert type 'System.Linq.IQueryable' to 'int' this error
}
Console.ReadLine();
}
}
Can you help me to solve this.If you did not understand what i explained please reply me
The following query is a sequence of elements, not a scalar value, even though you believe that there is only one result, it is still a collection with one element when the results of the query are iterated over:
var id1 = from val in db.Blogs
where val.Name == name
select val.BlobId;
Change this to:
int id1 = (from val in db.Blogs
where val.Name == name
select val.BlobId).First();
This query will execute immediately and return the first element in the sequence. It will throw an exception if there is no match, so you may want to use FirstOrDefault and assign to a nullable int instead.

Entity Framework Insert object with related object

I am a newbie with Entity Framework and I need to insert an object Comment that has a related FK object User into the database.
public Class Comment
{
public int CommentID { get; set; }
public string CommentContent { get; set; }
public virtual User User { get; set; }
public virtual DateTime CommentCreationTime { get; set; }
}
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public string UserImageUrl{get; set;}
public DateTime UserCreationDate { get; set; }
public virtual List<Comment> Comments { get; set; }
}
public void AddComment()
{
User user = new User() { UserID = 1 };
Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };
var ctx = new WallContext();
comments = new CommentsRepository(ctx);
comments.AddComment(comment);
ctx.SaveChanges();
}
Ideally, with T-SQL, if I know the PRIMARY KEY of my User object, I could just insert my Comment object and specify the PK of my 'User' in the insert statement.
I have tried to do the same with Entity Framework and it doesn't seem to work. It would be overkill to have to first fetch the User object from the database just to insert a new 'Comment'.
Please, how can I achieve this ?
You need to attach the user object to the context so that the context knows its an existing entity
public void AddComment()
{
var ctx = new WallContext();
User user = new User() { UserID = 1 };
ctx.Users.Attach(user);
Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };
comments = new CommentsRepository(ctx);
comments.AddComment(comment);
ctx.SaveChanges();
}

Resources