How to write an Edit Action

不羁的心 提交于 2020-01-06 19:40:55

问题


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 {}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12949409/how-to-write-an-edit-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!