当控制器';s不在模型中

本文关键字:模型 控制器 | 更新日期: 2023-09-27 18:28:17

我有我的型号

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作为模型。那么我如何从控制器引用这个对象呢?

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

在不创建新视图模型的情况下,有什么方法可以做到这一点吗?

当控制器';s不在模型中

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

 public ActionResult AddProductToCart_Details(Post post, FormCollection form)

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

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

然后得到这样的值。

var day = form["XXXX"];

如果您不想创建新的视图模型,可以向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操作将接受这个的对象

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

上面的jquery代码也将用于向这个版本的操作方法发送数据。

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);
        }