重构方法,asp.net mvc4

时间:2015-06-18 06:42:34

标签: c# asp.net asp.net-mvc

我有两种可能相同的方法,例如:

[HttpGet]
public ActionResult CreateDirectory(string designId, CreateDirectoryModel model)
{

    string customerSchema = SfsHelpers.StateHelper.GetSchema();
    TemplateLibraryEntry entry = GetTemplateLibraryEntry(model.DesignId, customerSchema);
    var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
    model.DesignId = designId;
    model.Directories = new List<string>();
    model.Directories.Add("/");
    model.Directories.AddRange(Directory.GetDirectories(path, "*", SearchOption.AllDirectories));
    for (int i = 1; i < model.Directories.Count; i++) {
        model.Directories[i] = model.Directories[i].Substring(path.Length).Replace('\\', '/');
    }
    model.Directories.Sort();

    return View(model);
}

和这个方法:

public void GetUploadFileFolders(UploadViewModel model, string designId)
{
    string customerSchema = SfsHelpers.StateHelper.GetSchema();
    TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
    var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
    model.DesignId = designId;
    model.Directories = new List<string>();
    model.Directories.Add("/");
    model.Directories.AddRange(Directory.GetDirectories(path, "*", SearchOption.AllDirectories));
    for (int i = 1; i < model.Directories.Count; i++) {
        model.Directories[i] = model.Directories[i].Substring(path.Length).Replace('\\', '/');
    }
    model.Directories.Sort();
}

但是有可能将这两种方法结合到一种方法中吗?

但如何结合这两种方法?

谢谢

但是如何改变这个:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UploadFile(UploadViewModel uploadViewModel)
    {
        CreateDirectoryModel model = new CreateDirectoryModel();
        try {
            GetUploadFileFolders(model, uploadViewModel.DesignId );
            //GetUploadFileFolders(uploadViewModel, uploadViewModel.DesignId);
            string validationError = null;

            bool fileUploaded = (uploadViewModel.UploadData != null) && (uploadViewModel.UploadData.ContentLength > 0) && !string.IsNullOrEmpty(uploadViewModel.UploadData.FileName);

            if (ModelState.IsValid && fileUploaded) {
                var extension = Path.GetExtension(uploadViewModel.UploadData.FileName).TrimStart('.');
                if (!Seneca.SfsLib.FileSystemHelper.UploadOptInExtensions.Contains(extension)) {
                    ViewBag.Message = Resources.Entity.DesignTemplate.NotAllowedExtension;
                    return View(uploadViewModel);
                }

                var fileName = Path.GetFileName(uploadViewModel.UploadData.FileName);

                TemplateLibraryEntry entry = GetTemplateLibraryEntry(uploadViewModel.DesignId, customerSchema);
                string folder = uploadViewModel.Directories[uploadViewModel.SelectedFolderId];
                var path = Path.Combine(Server.MapPath("~/"), entry.FilePath, folder.Replace('/', '\\').Trim('\\'), fileName);


                if (!System.IO.File.Exists(path)) {
                    uploadViewModel.UploadData.SaveAs(path);
                    return RedirectToAction(uploadViewModel.DesignId, "DesignTemplate/File");
                }

                validationError = Resources.Entity.DesignTemplate.FileAlreadyExists;
            }
            if (!fileUploaded)
                validationError = Resources.Entity.DesignTemplate.FileNotSelected;

            GetUploadFileFolders(model, uploadViewModel.DesignId);
            ViewBag.Message = validationError;
            return View(uploadViewModel);
        }
        catch (Exception ex) {
            Logger.Current.LogMessage(LogType.Warning, StateHelper.GetSchema(), LogCategory.Sfs, "Unable to upload file: {0}", ex.ToString());
            AddDelayedNotification(Resources.Entity.DesignTemplate.FileCouldNotBeUploaded, Notification.NotificationType.Error);
        }
        return View(uploadViewModel);
    }

3 个答案:

答案 0 :(得分:1)

您可以使用定义两个类所需部件的接口(或基类):

public interface IMyModel
{
    string DesignId { get; set; }
    List<string> Directories { get; set; }
}

您的类(或至少CreateDirectoryModel)必须实现接口:

public class CreateDirectoryModel : IMyModel
{
    // ...
}

在第二种方法中,您将参数类型更改为IMyModel,如下所示:

public void GetUploadFileFolders(IMyModel model, string designId)
{
    // ...
}

然后你可以用第一种方法调用第二种方法。

[HttpGet]
public ActionResult CreateDirectory(string designId, CreateDirectoryModel model)
{
    GetUploadFileFolders(model, designId);
    return View(model);
}

答案 1 :(得分:0)

您可以在UploadViewModel中创建一个属性,因为我看到两者中的所有属性都相同:

public class UploadViewModel
{

    CreateDirectoryModel createModel {get;set;}
}

public void GetUploadFileFolders(CreateDirectoryModel model, string designId)
{
    string customerSchema = SfsHelpers.StateHelper.GetSchema();
    TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
     var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
     model.DesignId = designId;
     model.Directories = new List<string>();
     model.Directories.Add("/");
     model.Directories.AddRange(Directory.GetDirectories(path, "*", SearchOption.AllDirectories));
     for (int i = 1; i < model.Directories.Count; i++) 
     {
        model.Directories[i] = model.Directories[i].Substring(path.Length).Replace('\\', '/');
     }

     model.Directories.Sort();

}

并在你的行动中:

[HttpGet]
public ActionResult CreateDirectory(string designId, CreateDirectoryModel model)
{
    GetUploadFileFolders(model,designId)
    return View(model);
}

当将它用于UploadViewModel时,您现在可以:

GetUploadFileFolders(model.creatModel,designId);

答案 2 :(得分:0)

使用基于约定的映射器Automapper,您可以将它们组合为

    [HttpGet]
    public ActionResult CreateDirectory(string designId, CreateDirectoryModel model)
    {

        string customerSchema = SfsHelpers.StateHelper.GetSchema();
        TemplateLibraryEntry entry = GetTemplateLibraryEntry(model.DesignId, customerSchema);
        var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
        model.DesignId = designId;
        model.Directories = new List<string>();
        model.Directories.Add("/");
        model.Directories.AddRange(Directory.GetDirectories(path, "*", SearchOption.AllDirectories));
        for (int i = 1; i < model.Directories.Count; i++) {
            model.Directories[i] = model.Directories[i].Substring(path.Length).Replace('\\', '/');
        }
        model.Directories.Sort();
        //
        Mapper.CreateMap<CreateDirectoryModel,UploadViewModel>();
        var uploadmodel=Mapper.Map<UploadViewModel>(model);
        uploadmodel.Directories.Sort();
        //
        return View(model);
    }

但是我建议你,如果这两个类不是专门的,那么使用其中一个,从而减少redundency