email driven image upload on imgur - email

I'm using mandrill for managing email service, and it's features of inbound email webhook (HTTP POST) for retrieving the attached image.
Details of Mandrill inbound webhook.
http://help.mandrill.com/forums/21092258-Inbound-Email-Basics
I've tried to get the HTTP inbound webhook but unable to deserialize it into json, and unable to retrieve the attached image.
I've used class and method from following github link.
https://github.com/martydill/mandrill-inbound-classes
after fetching the attached image I need to upload it to imgur website using API,
Am able to upload images to imgur website but i'm facing problem while retrieving attachment from inbound webhook from mandrill.
kindly help me as soon as possible.

I've gone through the class as you stated in github and I've added one more field in the class to get the attachment value from the email.
here is the required class for mandrill webhook.
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Mandrill
{
public class MailEvent
{
[JsonProperty(PropertyName = "ts")]
public string TimeStamp { get; set; }
[JsonProperty(PropertyName = "event")]
public string Event { get; set; }
[JsonProperty(PropertyName = "msg")]
public Message Msg { get; set; }
}
public class Message
{
[JsonProperty(PropertyName = "raw_msg")]
public string RawMessage { get; set; }
[JsonProperty(PropertyName = "headers")]
public Header Header { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "html")]
public string Html { get; set; }
[JsonProperty(PropertyName = "from_email")]
public string FromEmail { get; set; }
[JsonProperty(PropertyName = "from_name")]
public string FromName { get; set; }
// Not sure why Mandrill sends an array of arrays here...
[JsonProperty(PropertyName = "to")]
public string[][] To { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
[JsonProperty(PropertyName = "tags")]
public string[] Tags { get; set; }
[JsonProperty(PropertyName = "sender")]
public string Sender { get; set; }
[JsonProperty(PropertyName = "dkim")]
public DKIM DKIM { get; set; }
[JsonProperty(PropertyName = "spf")]
public SPF SPF { get; set; }
[JsonProperty(PropertyName = "spam_report")]
public SpamReport SpamReport { get; set; }
//[JsonProperty(PropertyName = "attachments")]
//public attachments attachments { get; set; }
[JsonProperty(PropertyName = "attachments")]
public IDictionary<string, IDictionary<string,string>> attachments { get; set; }
}
[JsonDictionary()]
public class Header : Dictionary<string, object>
{
// Need to find a nicer way of doing this... Dictionary<string, object> is kinda dumb
}
public class attachments
{
[JsonProperty(PropertyName = "name ")]
public string name { get; set; }
[JsonProperty(PropertyName = "type ")]
public string type { get; set; }
[JsonProperty(PropertyName = "content ")]
public string content { get; set; }
[JsonProperty(PropertyName = "base64 ")]
public bool base64 { get; set; }
}
public class SpamReport
{
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "matched_rules")]
public SpamRule[] MatchedRules { get; set; }
}
public class SpamRule
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
public class DKIM
{
[JsonProperty(PropertyName = "signed")]
public bool Signed { get; set; }
[JsonProperty(PropertyName = "valid")]
public bool Valid { get; set; }
}
public class SPF
{
[JsonProperty(PropertyName = "result")]
public string Result { get; set; }
[JsonProperty(PropertyName = "detail")]
public string Detail { get; set; }
}
}
and you have to call the imgur api like this.
[HttpPost]
[ValidateInput(false)]
public ActionResult past_mandrill(FormCollection fc)
{
string json = fc["mandrill_events"];
//SqlConnection con = new SqlConnection(WebConfigurationManager.AppSettings[0]);
var events = JsonConvert.DeserializeObject<IEnumerable<Mandrill.MailEvent>>(json);
foreach (var mailEvent in events)
{
//Label2.Text = Label2.Text + mailEvent.Msg.To[0][0] + "<br>";
try
{
foreach (KeyValuePair<string, IDictionary<string, string>> attch in mailEvent.Msg.attachments)
{
//Label2.Text = Label2.Text + attch.Key + "<br>";
byte[] temp;
string albumid = "zBBCDbRcNhE493I"; //use your own album id where you want to store the image.
foreach (KeyValuePair<string, string> attchcnt in attch.Value)
{
//Label2.Text = Label2.Text + attchcnt.Key + " " + attchcnt.Value + "<br>";
if (attchcnt.Key.Equals("content"))
{
using (var w = new WebClient())
{
string base64String = "";
base64String = attchcnt.Value.ToString();
var values = new NameValueCollection
{
{"image", base64String},
{"album", albumid}
};
w.Headers.Add("Authorization", "Client-ID dac37a6b08b4974"); // user your own client-id of imgur website
byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
temp = response;
}
}
}
}
}
catch (Exception e)
{
}
//Label2.Text = mailEvent.Msg.attachments.Values.ToString();
}
return new HttpStatusCodeResult((int)HttpStatusCode.OK);
}

Related

Entity Framework not saving update for just one property on just one Entity Type

I am using ASP.Net Core MVC and Entity Framework Core in Visual Studio 2017.
We are using a pretty straight forward Repository Pattern.
I'm eight months into this project and this is the first time I am having this strange problem on this one property on this one entity getting saved to the Database on SaveChanges after UpdateChanges.
So here is the flow.
1) I have a Create controller action to save a new entity called Recommendation.
The Recommendation has a parent entity called finding.
When I create a new recommendation I have to update the status on the parent finding. Also the Finding entity has a parent Entity called Audit.
When I edit the finding status I also have to update the audit status.
Here is some code for this.
[HttpPost]
public IActionResult Create(CreateIntRecommendationVM createIntRecommendationVM)
{
int findingId = createIntRecommendationVM.Finding.FindingId;
Finding finding = _findingRepo.Findings
.Include(f => f.Audit)
.Where(f => f.FindingId == findingId)
.FirstOrDefault();
if (RecModelStateIsValid(ModelState))
{
ClaimsPrincipal user = HttpContext.Request.HttpContext.User;
short staffId = short.Parse(user.Claims.Single(c => c.Type == "StaffId").Value);
Recommendation recommendation = createIntRecommendationVM.Recommendation;
recommendation.RecFindingId = findingId;
#region Get Recommendation Number
recommendation.RecCd = GetRecommendationNumber(findingId);
#endregion
recommendation.RecStatusId = 10;
recommendation.RecStaffId = staffId;
recommendation.RecLastUpdateDt = DateTime.Now;
_recommendationRepo.Add(recommendation);
_recommendationRepo.SaveChanges();
bool unresolvedFinding = false;
bool unresolvedAudit = false;
int? oldFindingStatus = finding.FindingStatusId;
if (finding.FindingStatusId != 10)
{
finding.FindingStatusId = 10;
unresolvedFinding = true;
}
if (oldFindingStatus != 10 && finding.Audit.StatusID != 10)
{
finding.Audit.StatusID = 10;
unresolvedAudit = true;
}
_findingRepo.Update(finding);
_findingRepo.SaveChanges();
When I run in debug mode and put a break point and inspect while I am stepping through, I am definately setting finding.FindingStatusId to 10 and finding.Audit.StatusID to 10.
_findingRepo.Update(finding);
hits this repo:
public class FindingRepository : IFindingRepository
{
private ApplicationDbContext context;
public FindingRepository(ApplicationDbContext ctx)
{
context = ctx;
}
public IQueryable<Finding> Findings => context.Findings;
public Finding Get(int id)
{
Finding finding = context.Findings.Find(id);
return finding;
}
public void Add(Finding finding)
{
context.Findings.Add(finding);
}
public void Update(Finding finding)
{
context.Findings.Update(finding);
}
public void Delete(int id)
{
context.Database.ExecuteSqlCommand("sp_delete_finding_int #finding_id = {0}", id);
}
public void SaveChanges()
{
context.SaveChanges();
}
}
So here is the weird part.
finding.Audit.StatusID is getting updated in the DB.
finding.FindingStatusId is not.
So for the entity, "finding" that I am sending to the repo's Update method, the "FindingStatusId" for the entity being updated is not getting saved.
But, the "finding" entity's parent, "Audit", the "StatusID" is getting saved.
I can't for the life of me figure out what is going on here.
For completeness I'll post the Finding and Audit Entity Models.
[Table("finding")]
public class Finding
{
private string _findingText;
[Key]
[Column("finding_id")]
public int FindingId { get; set; }
[Column("finding_audit_id")]
public int FindingAuditId { get; set; }
[Column("finding_cd")]
[Display(Name = "Finding #")]
[StringLength(15)]
public string FindingCd { get; set; }
[Column("finding_tx")]
[Required(ErrorMessage = "Description Required")]
[StringLength(7000)]
public string FindingText
{
get
{
return _findingText;
}
set
{
_findingText = value?.Trim();
}
}
[Column("finding_page_cd")]
[StringLength(100)]
public string FindingPageCd { get; set; }
[Column("finding_joint_cd")]
public string FindingJointCd { get; set; }
[Column("finding_compliance_tx")]
[StringLength(20)]
public string FindingComplianceText { get; set; }
[Column("finding_prior_year_cd")]
[Display(Name = "Repeat Finding")]
public string FindingPriorYearCd { get; set; }
[Column("finding_decision_cd")]
public string FindingDecisionCd { get; set; }
[Column("finding_request_decision_cd")]
public string FindingRequestDecisionCd { get; set; }
[Column("finding_decision_ogc_concur_cd")]
public string FindingDecisionOgcConcurCd { get; set; }
[Column("finding_pdl_id")]
public int? FindingPdlId { get; set; }
[Display(Name = "Significant")]
[Column("finding_significant_cd")]
public string FindingSignificantCd { get; set; }
[Column("finding_on_stay_cd")]
public string FindingOnStayCd { get; set; }
[Column("finding_stay_request_cd")]
public string FindingStayRequestCd { get; set; }
[Column("finding_last_update_dt")]
public DateTime FindingLastUpdateDate { get; set; }
[Column("finding_update_staff_id")]
public short? FindingUpdateStaffId { get; set; }
[Column("finding_cd_org")]
public string FindingCdOrg { get; set; }
[NotMapped]
public string RepeatingYearsDisplayList
{
get
{
if (RepeatingYears?.Count > 0)
{
string repeatingYears = string.Empty;
RepeatingYears.ForEach(ry =>
repeatingYears += $"{ry.FindingFyCd}, ");
return repeatingYears.Remove(repeatingYears.Length - 2);
}
return string.Empty;
}
}
#region Navigation Properties
[Column("finding_finding_type_id")]
public short? FindingTypeId { get; set; }
[ForeignKey("FindingTypeId")]
public FindingType FindingType { get; set; }
[Column("finding_status_id")]
public int? FindingStatusId { get; set; }
[ForeignKey("FindingStatusId")]
public Status FindingStatus { get; set; }
public List<FindingFiscalYear> RepeatingYears { get; set; }
public List<Recommendation> Recommendations { get; set; }
[ForeignKey("FindingAuditId")]
public Audit Audit { get; set; }
#endregion
}
[Table("audit")]
public class Audit
{
private string _auditAcnCd;
private string _title;
private string _summary;
[Key]
[Column("audit_id")]
public int AuditID { get; set; }
[Required(ErrorMessage = "ACN Required")]
[Display(Name="ACN:")]
[Column("audit_acn_cd")]
public string AuditAcnCd
{
get
{
return _auditAcnCd;
}
set
{
_auditAcnCd = value?.Trim();
}
}
[Required(ErrorMessage = "Title Required")]
[Display(Name = "Title:")]
[Column("audit_report_title_tx")]
public string Title
{
get
{
return _title;
}
set
{
_title = value?.Trim();
}
}
[Required(ErrorMessage = "Issuer Required")]
[Display(Name="Issuer:")]
[Column("audit_issuer_tx")]
public string Issuer { get; set; }
[Display(Name = "Sensitive Designation")]
[Column("audit_sensitive_cd")]
public string AuditSensitiveCode { get; set; }
[Display(Name = "Alternative Product")]
[Column("audit_alternate_product_cd")]
public string AuditAlternateProductCode { get; set; }
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Priority must be a number.")]
[Display(Name = "Priority:")]
[Column("audit_priority_cd")]
public short? Priority { get; set; }
[StringLength(maximumLength: 1000,ErrorMessage = "Max Length: 1000")]
[Display(Name = "Summary:")]
[Column("audit_summary_tx")]
public string Summary
{
get
{
return _summary;
}
set
{
_summary = value?.Trim();
}
}
[Column("audit_gao_contact_tx")]
[Display(Name = "GAO Contact:")]
[StringLength(maximumLength: 200, ErrorMessage = "Max Length: 200")]
public string AuditGaoContactText { get; set; }
[Column("audit_gao_job_cd")]
[Display(Name = "GAO Job Code:")]
[StringLength(maximumLength: 200, ErrorMessage = "Max Length: 30")]
public string AuditGaoJobCode { get; set; }
[Display(Name = "Lead Office:")]
[Column("audit_lead_office_id")]
public short? LeadOfficeID { get; set; }
#region Navigation Properties
[Required(ErrorMessage = "Audit Type Required.")]
[Display(Name = "Audit Type:")]
[Column("audit_audit_type_id")]
public short AuditTypeID { get; set; }
[Display(Name = "Audit Type:")]
public AuditType AuditType { get; set; }
[Column("audit_status_id")]
public int StatusID { get; set; }
public Status Status { get; set; }
[Required(ErrorMessage = "Office is Required.")]
[Display(Name = "Offices:")]
[Column("audit_office_id")]
public short? OfficeID { get; set; }
public Office Office { get; set; }
[ForeignKey("AuditID")]
public External External { get; set; }
public IEnumerable<AuditLog> AuditLogs { get; set; }
public IEnumerable<Finding> Findings { get; set; }
public IEnumerable<Assignment> Assignments { get; set; }
[Column("audit_update_staff_id")]
public short UpdateStaffID { get; set; }
[Column("audit_oig_manager_id")]
[Display(Name = "OIG Audit Manager:")]
public short? OigAuditManagerId { get; set; }
[Display(Name = "OIG Audit Manager:")]
[ForeignKey("OigAuditManagerId")]
public Staff OigAuditManager { get; set; }
[Column("audit_fsa_office_id")]
[Display(Name = "FSA Audit Lead:")]
public int? FsaLeadOfficeId { get; set; }
[Display(Name = "FSA Audit Lead:")]
[ForeignKey("FsaLeadOfficeId")]
public FSAOffice FsaLeadOffice { get; set; }
[ForeignKey("LeadOfficeID")]
public Office LeadOffice { get; set; }
#endregion
}
Well just as I was hoping I opened it back up this morning, started fresh, and it's working.
Ivan, I believe you are right. You don't need to call Update for Entity Framework. I've noticed this before if I forget the Update statement.
And if you don't need to you are making a call to update in the repo for no reason.
I was resetting scenarios by hand in the DB to test this over and over. Something must have gotten corrupt.
But all the code above is working if it helps anyone.

Adding new related entities in a single action

Every riddle has one or more questions, how can add both a Riddle and a Question to that riddle by submitting a single form?
This is RiddlesController Create action code:
public ActionResult Create(RiddleViewModel model)
{
if (ModelState.IsValid)
{
try
{
_db.Riddles.Add(new Models.Riddle
{
Name = model.Name,
Description = model.Description ,
CreationDate = DateTime.Now,
User = _db.Users.Find(User.Identity.GetUserId()),
});
_db.Questions.Add(new Models.Question
{
Body = model.FirstQuestionBody,
Answer = model.FirstQuestionAnswer,
CreationDate = DateTime.Now,
// What should I write here? or is there any better way to accomplish this?
Riddle = ?????
});
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
This is Riddle model code:
public class Riddle
{
public int Id { get; set; }
public string Name { get; set; }
[MaxLength(200)]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public List<Review> Reviews { get; set; }
[Required]
public ApplicationUser User { get; set; }
public virtual List<Question> Questions { get; set; }
[Column(TypeName = "datetime2")]
public DateTime CreationDate { get; set; }
}
This is Question model code:
public class Question
{
public int Id { get; set; }
public string Body { get; set; }
public string Answer { get; set; }
public Riddle Riddle { get; set; }
[Column(TypeName ="datetime2")]
public DateTime CreationDate { get; set; }
}
This is RiddleViewModel code:
public class RiddleViewModel
{
[Required]
public string Name { get; set; }
[MaxLength(200)]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
// Question properties
[DataType(DataType.MultilineText)]
public string FirstQuestionBody { get; set; }
public string FirstQuestionAnswer { get; set; }
}
You can try as shown below.
_db.Questions.Add(new Models.Question
{
Body = model.FirstQuestionBody,
Answer = model.FirstQuestionAnswer,
CreationDate = DateTime.Now,
Riddle = new Models.Riddle
{
Name = model.Name,
Description = model.Description ,
CreationDate = DateTime.Now,
User = _db.Users.Find(User.Identity.GetUserId()),
}
});
_db.SaveChanges();

Post Json Data to Rest API

I'm developing WP8 app and i'm new to it.. i want to know my post method is correct or not because i'm unable to post my data in the url it produces an exception..
My Class Contents...
public class Register
{
public int id { get; set; }
public string password_reset_hash { get; set; }
public string temp_password { get; set; }
public bool remember_me { get; set; }
public string activation_hash { get; set; }
public string ip_address { get; set; }
public bool status { get; set; }
public bool activated { get; set; }
public string permissions { get; set; }
public DateTime last_login { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string email { get; set; }
public string password { get; set; }
public string conformpassword { get; set; }
public string username { get; set; }
}
here is my code..
public void btn_register_click(object sender, RoutedEventArgs e)
{
string url="myurl";
Register res=new Register();// my class
res.email = txt_email.Text;
res.password = txt_password.Text;
res.conformpassword = txt_conf_psswrd.Text;
res.username = txt_username.Text;
res.created_at = DateTime.Now;
res.last_login = DateTime.Now;
res.updated_at = DateTime.Now;
res.status = true;
json = JsonConvert.SerializeObject(res);
WebClient wc = new WebClient();
var URI = new Uri(url);
wc.Headers["Content-Type"] = "application/json";
wc.Headers["ACCEPT"] = "application/json";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI, "POST", json);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString()); //i'm getting error here..
}
}
My Screen Design..
Error is..
Thanks
It looks to me like there is a problem with the URI you are using. The error message you posted shows the server returning a "Not found" header. Maybe it just is not quite correct? I did not see the exact URI in the code you posted. string url="myurl"; does not look like this is the url you want to use.
That's also why you can't access the response stream without an exception with this line: MessageBox.Show(e.Result);. There just is no valid response. This is documented here: http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs.result%28v=vs.110%29.aspx.
You can determine if such an error occurred by checking the Error property of UploadStringCompletedEventArgs (http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs%28v=vs.110%29.aspx).

Update only a single column using EF5 in MVC4

I have an UserProfile model
public class UserProfile
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Key]
[Required]
public string EmailAddress { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
[Required]
public string BusinessUnit { get; set; }
[Required]
public string JobRole { get; set; }
public bool IsEnabled { get; set; }
public string Password { get; set; }
}
I want to update only the password field.
This is the code I am trying
if (ModelState.IsValid)
{
var context = new JhaDbContext();
using (JhaDbContext jdc = new JhaDbContext())
{
try
{
jdc.UserProfiles.Attach(userProfile);
userProfile.Password = model.NewPassword;
jdc.SaveChanges();
httpStatus = HttpStatusCode.OK;
}
catch (InvalidOperationException ioe)
{
httpStatus = HttpStatusCode.BadRequest;
}
catch (DbEntityValidationException ev)
{
httpStatus = HttpStatusCode.BadRequest;
}
}
}
I get the DbEntityValidationException on the required fields. Please guide me in solving this.
Regards
Sudheep
I usually would do a
var myEntity = jdc.(tableName).find(userID);
then set
myEntity.Password = "new password";
jdc.Entry(userProfile).State = System.Data.EntityState.Modified;
/* why do you have it as unchanged? */
jdc.saveChanges()

How to write an Edit Action

I am trying to come up with an edit action. See below for what i have so far.
ViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GlobalUnitedSC.WebUI.Models
{
public sealed class CreateMensPlayerViewModel
{
//Player profile starts here
[HiddenInput(DisplayValue=false)]
public int MensTeamId { get; set; }
[HiddenInput(DisplayValue = false)]
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime? BirthDate { get; set; }
[Required]
public string Position { get; set; }
public int ShirtNumber { get; set; }
[DataType(DataType.Date)]
public DateTime? Joined { get; set; }
public string Country { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
//Player Statistics starts here
public int Games { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
public int TotalShots { get; set; }
public int ShotsOnGoal { get; set; }
public int FoulsDrawn { get; set; }
public int FoulsCommitted { get; set; }
public int Saves { get; set; }
public int BlueCards { get; set; }
public int YellowCards { get; set; }
public int RedCards { get; set; }
}
}
Create Actions:
[HttpGet]
public ActionResult Create(int mensTeamId)
{
new CreateMensPlayerViewModel {MensTeamId = mensTeamId};
return View();
}
[HttpPost]
public ActionResult Create(CreateMensPlayerViewModel viewModel, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
var mensTeam = _dataSource.MensTeams.Single(t => t.Id == viewModel.MensTeamId);
var mensPlayer = new MensPlayer
{
Name = viewModel.Name,
BirthDate = viewModel.BirthDate,
Position = viewModel.Position,
ShirtNumber = viewModel.ShirtNumber,
Joined = viewModel.Joined,
Country = viewModel.Country,
Description = viewModel.Description,
EmailAddress = viewModel.EmailAddress,
PhoneNumber = viewModel.PhoneNumber,
Games = viewModel.Games,
Goals = viewModel.Goals,
Assists = viewModel.Assists,
TotalShots = viewModel.TotalShots,
ShotsOnGoal = viewModel.ShotsOnGoal,
FoulsDrawn = viewModel.FoulsDrawn,
FoulsCommitted = viewModel.FoulsCommitted,
Saves = viewModel.Saves,
BlueCards = viewModel.BlueCards,
YellowCards = viewModel.YellowCards,
RedCards = viewModel.RedCards
};
mensTeam.MensPlayers.Add(mensPlayer);
_dataSource.Save();
TempData["message"] = string.Format("{0} has been saved", mensPlayer.Name);
return RedirectToAction("detail", "MensTeam", new {id = viewModel.MensTeamId});
}
return View(viewModel);
}
HttpGet Edit Action
[HttpGet]
public ActionResult Edit (int id)
{
var mensPlayer = _dataSource.MensPlayers.FirstOrDefault(p => p.Id == id);
return View(mensPlayer);
}
Now could anyone please help me with the HttpPost Edit action, preferably one based on the model class mentioned above?
I was hoping it has something to do with the line below, if this creates a new player, what could i write to edit that player?
var mensPlayer = new MensPlayer {}
Since it's a post the method is kind of equal to your create-method. You will receive a MensPlayer as a parameter.
Than you check if the Model is valid (validation etc.) and flag the entry as modified and save the changes.
[HttpPost]
public ActionResult Edit(MyModel myModel)
{
if (ModelState.IsValid)
{
DbContext.Entry(myModel).State = EntityState.Modified;
DbContext.SaveChanges();
return RedirectToAction("Index");
}
return View(myModel);
}
DBContext
public class ModelContext : DbContext
{
public DbSet<MyModel> MyModelSet{ get; set; }
}
More info about DBContext.
With help of Slauma in the comments in the repost or extension of this question at:
Repost/Extension
This is what he suggested i do and it works.
Add to IDataSource Interface:
void Update(MensPlayer mensPlayer);
Update Implemented in Db class:
void IDataSource.Update(MensPlayer mensPlayer)
{
Entry(mensPlayer).State = EntityState.Modified;
}
Edit Action:
[HttpPost]
public ActionResult Edit(MensPlayer mensPlayer)
{
if (ModelState.IsValid)
{
//Save Player
_dataSource.Update(mensPlayer);
_dataSource.Save();
TempData["message"] = string.Format("{0} has been saved", mensPlayer.Name);
return RedirectToAction("Detail", "MensPlayer", new {id = mensPlayer.Id});
}
return View(mensPlayer);
}
And Just like that all works fine, although i was under the assumption that i would implement Update to the whole DbSet like i did with Save.