【问题标题】:How to pass additional value to controller when it's not in the model?当控制器不在模型中时,如何将附加值传递给控制器​​?
【发布时间】:2015-12-26 20:29:44
【问题描述】:

我有我的模型

public class Post
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }
}

public class Photo
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public string Source { get; set; }
}

public class PhotoAttach
{
    [Key]
    public int Id { get; set; }

    public virtual Post Post { get; set; }

    public virtual Photo Photo { get; set; }

    public bool IsThumbnail { get; set; }
}

在我的CreatePost 视图中,我希望用户能够选择一些现有照片以附加到创建帖子中。我使用一些脚本进行了此操作,因此当用户单击提交按钮时,我已经有一个 JSON 对象,其中包含将要附加的所有照片 ID。

但是这个视图使用Post作为模型。那么如何从控制器中引用这个对象呢?

我想将其转换为字符串并添加一些隐藏的输入。但是可以从控制器访问它吗?

有没有办法在不创建新视图模型的情况下做到这一点?

【问题讨论】:

  • 渲染视图时使用的模型与用作控制器操作输入的模型无关。它们可以是不同的模型。
  • 您可以将 listphotoIds 作为额外参数添加到 CreatePost 视图。公共类 CreatePost(Post post, list photoIds){ ... 代码在这里 }
  • @HastaPasta 但是如何在提交表单时从视图中传递该参数?

标签: c# asp.net-mvc


【解决方案1】:

是的,这是可能的。 你的动作结果是这样的

 public ActionResult AddProductToCart_Details(Post post, FormCollection form)

您可以将值保存在 html 中的隐藏名称中。

<input id="formCheck" type="checkbox" name="xxxx" /> 

然后像这样得到那个值。

var day = form["XXXX"];

【讨论】:

    【解决方案2】:

    如果您不想创建新的视图模型,可以在 HttpPost 操作方法中添加一个新参数以接受文件 ID 的集合。

    [HttpPost]
    public ActionResult CreatePost(Post model,IEnumerable<int> fileIds)
    {
        // you can loop through fileIds colleciton
        return Json(new { status="success"});
    }
    

    假设您发送数据的 ajax 代码包括 fileIds 属性,它是您的文件 ID 的数组。

    $(function () {
    
        $("yourFormId").submit(function (e) {
    
            e.preventDefault();
            var fileIdsToSend= [345, 56, 234]; //Array of Id's you want to send 
            var _f = $(this);
            var data = {
                Title: $("#Title").val(),
                Description :$("#Description").val(),
                fileIds: fileIdsToSend
            };
    
            $.post(_f.attr("action"),data, function (response) {
               // do something with the response
            });
    
        });             
    
    });
    

    理想的解决方案是使用特定于您的视图的视图模型,而不是使用实体模型作为视图模型。

    public class CreatePostVm
    {
      public string Title {set;get;}
      public string Description {set;get;}
      public IEnumerable<int> FileIds {set;get;}
    }
    

    您的 HttpPost 操作将接受 this 的对象

    [HttpPost]
    public ActionResult CreatePost(CreatePostVm model)
    {
      // do something and return something
    }
    

    上面的 jquery 代码也可以用于向这个版本的 action 方法发送数据。

    【讨论】:

    • 不使用ajax和view model可以吗?
    • 就是,保持表单字段名称与属性名称相同。(FileIds)。但我建议通过视图模型路线。
    【解决方案3】:
    var PhootoIdList = GetAllYourPhotoIds;
    var PostModel = {
        Title : GetTitle,
        Description : GetDescription
    };
    $.ajax({
        url: '/mycontroller/action',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            photoIds: PhotoIdList,
            model: {
                Post: PostModel
            }
        }),
        success: function(result) {
    
        }
    });
    

    没有 Ajax

    @using(Html.BeginForm("Create", "Posts", FormMethod.Post, null) )
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>Post</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <select name="photoIds" id="photoIds" multiple>
                <option value="AAAA">Photo 1</option>
                <option value="BBBB">Photo 2</option>
                <option value="CCCC">Photo 3</option>
            </select>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Title,Description")] Post post, string[] photoIds)
            {
                if (ModelState.IsValid)
                {
                    db.Posts.Add(post);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(post);
            }
    

    【讨论】:

    • 不使用ajax可以吗?
    • @using(Html.BeginForm("action", "controller", new { PhotoIds = "GetPhotoIdsHere" }, FormMethod.Post, null)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-07-03
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多