首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将html fileupload值传递给MVC 5中的c#方法以绑定到部分视图

将html fileupload值传递给MVC 5中的c#方法以绑定到部分视图
EN

Stack Overflow用户
提问于 2018-06-13 01:56:42
回答 1查看 0关注 0票数 0

有一个主视图,其中包含两个选项卡,它们需要相同的表视图模型。但是,我创建了一个包含表结构的部分视图,用于异步地在两个选项卡中显示数据记录。一个选项卡从CSV获取数据,而另一个选项卡根据用户的选择从SQLServer获取数据,但具有相同的模型。

我有以下概念的屏幕截图:红色框描绘了部分视图,它有两个按钮,一个将表数据提交到数据库,另一个是在需要时添加更多的记录;

我的挑战是:我有一个类方法,需要从FileUpload值并将数据绑定到部分视图上的模型。

请参见下面的模型结构:

[Table("atm")]
public class ATM
{
    public ATM()
    {
        this._EJTransactions = new HashSet<EJTransaction>();
        this._CassetteSettings = new HashSet<CassetteSetting>();
        this._EJFileDownloads = new HashSet<EJFileDownload>();
        this._CamFileDownloads = new HashSet<ImageFileDownload>();
        this._TransImages = new HashSet<TransImage>();
        this._UserAtms = new HashSet<UserAtms>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int atmId { get; set; }
    [ForeignKey("ATMVendor")]
    public int vendorId { get; set; }
    [ForeignKey("BankBranch")]
    public int branchId { get; set; }
    [MaxLength(50)]
    [Index("ix_uniq_terminal", 1, IsUnique = true)]
    [DisplayName("Terminal ID")]
    public string terminalId { get; set; }
    [MaxLength(30)]
    [Index("ix_uniq_ip", 1, IsUnique = true)]
    [DisplayName("IP")]
    public string ip { get; set; }
    [MaxLength(100)]
    [Index("ix_uniq_title", 1, IsUnique = true)]
    [DisplayName("Title")]
    public string title { get; set; }
    [DisplayName("EJ Enabled")]
    public bool ejEnabled { get; set; }
    [DisplayName("Image Enabled")]
    public bool camEnabled { get; set; }
    [DisplayName("IsActive")]
    public bool isActive { get; set; }

    public virtual ATMVendor ATMVendor { get; set; }
    public virtual BankBranch BankBranch { get; set; }

    public virtual ICollection<EJTransaction> _EJTransactions { get; set; }
    public virtual ICollection<CassetteSetting> _CassetteSettings { get; set; }
    public virtual ICollection<EJFileDownload> _EJFileDownloads { get; set; }
    public virtual ICollection<ImageFileDownload> _CamFileDownloads { get; set; }
    public virtual ICollection<TransImage> _TransImages { get; set; }
    public virtual ICollection<UserAtms> _UserAtms { get; set; }
}

部分视图绑定到此模型。

public class CSVAtmLoader
{
    public IEnumerable<ATM> Read(string csvfile)
    {
        List<ATM> atmlist = new List<ATM>();
        TextReader csvReader = new StreamReader(csvfile);
        var csv = new CsvReader(csvReader, false);

        csv.Configuration.DetectColumnCountChanges = true;
        csv.Configuration.RegisterClassMap<AtmMap>();

        //csv.Configuration.InjectionCharacters = new[] { '=', '@', '+', '-' };
        //csv.Configuration.SanitizeForInjection = false;
        //csv.Configuration.InjectionEscapeCharacter = '\t';

        var atms = csv.GetRecords<ATM>();
        foreach (var atm in atms)
        {
            atm.branchId = GetBranchId(atm.BankBranch.branch);
            atm.vendorId = GetVendorId(atm.ATMVendor.vendor);
            atmlist.Add(atm);
        }
        return atmlist;
    }

    private int GetBranchId(string branch)
    {
        BankBranch br = new BankBranch { branch = branch }.SelectBranch();
        return 0;
    }

    private int GetVendorId(string vendor)
    {
        return 0;
    }
}

在父视图中,我有一个CSVAtm选项卡,该选项卡承载了部分视图,我的进度被阻止了,以实现布局的动态性。请参见从FileUpload控件中选择的用csvfile呈现部分视图的父视图:

<div class="tab-pane fade" id="csvAtm">
     <p>
        <div class="form-inline">
           <table>
              <tr>
                <td><span> Choose a File:</span>&nbsp;&nbsp;</td>
                <td><input id="csvfile" type="file" name="file" class="btn btn-default" onchange="clear();"/></td>
                <td>&nbsp;&nbsp;</td>
                <td>
                   <input class="btn btn-default col-mid-2" type="button" id="upload" value="Upload" onclick="uploadfile();" />
                </td>
            </tr>
        </table>
     </div>
     <div id="error"></div>
     <br />
     <div class="form-group">

       @{
          if (string.IsNullOrEmpty(filename))
          {
            //this is where my challenge is, how to get the filename from fileupload 
            //I know this is executed at the server side and hence, the client is not aware of server side scripting 
            Html.RenderPartial("LoadedAtms", new CSVAtmLoader().Read(filename));
          }
       }
 </div>
EN

Stack Overflow用户

发布于 2018-06-13 10:59:37

首先,转换部分视图的模型,以便它只是一个哑对象(POCO)来保存数据。填充模型的所有工作都由控制器来处理-通过这种方式,可以为两个数据源提供一个视图和一个模型。

public class AtmViewModel
{
    public string Vendor { get; set; }
    public string Branch { get; set; }
    public string IP { get; set; }
    public bool IsActive { get; set; }
    ...
}

和部分视图(AtmList.cshtml)

@model IEnumerable<AtmViewModel>

<table>
@foreach(var atm in Model)
{
    <tr>
        <td>@atm.Vendor</td>
        <td>@atm.Branch</td>
        <td>@atm.IP</td>
        <td>@Html.DisplayFor(m => atm.IsActive)</td>
    </tr>
}

我会把CSV上传表单移出这个部分视图。

主父视图(Index.cshtml)

@model IndexViewModel

<div>
    @using(Html.BeginForm("Upload", "AtmController",
                          new { },
                          FormMethod.Post,
                          new { @class="form", enctype="multipart/form-data" })
    {
        <input type="file" name="csvFile" />
        <button type="submit">Upload</button>
    })
</div>
<div id="results">
    @Html.PartialView("AtmList", Model.Atms)
</div>

<script>
    ...
</script>

及其模型

public class IndexViewModel
{
    public AtmViewModel Atms { get; set; }
    ...
}

在第一次加载时,表将从数据库中填充。

public ActionResult Index(int id)
{
    var atms = db.GetAtms(id);
    var model = new IndexViewModel
                {
                    Atms = atms
                    ...
                };

    return View(model);
}

或者进行另一个单独的调用来填充另一个选项卡。

public ActionResult Index()
{
    return View();
}

public ActionResult GetAmts(int id)
{
    var atms = db.GetAtms(id);

   return PartialView("AtmList", atms);
}

当表单提交时,您将csv反序列化并返回parital视图。

[HttpPost]
public ActionResult Upload(HttpPostedFileBase csvFile)
{
    List<AtmViewModel> atms = CSVAtmLoader.LoadFile(csvFile);

    return ParitalView("AtmList", atms);
}

我把解析CSV作为读者的练习。

为了防止导航或页面重新加载,我们将使用Ajax提交表单,并使用新的部分视图内容交换div的内容。

$("form").on("submit", function(e)
{
    e.preventDefault();
    var form = $(this);
    var formdata = new FormData(form.get(0));

    $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),            
        processData: false,
        contentType: false
    })
    .then(function(partialViewResult)
    {
        $("#results").html(partialViewResult);
    });
}

考虑完全避免CSV上传。使用客户端JavaScript将CSV“上载”转换为JSON,然后用JavaScript构建部分视图html。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档