Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在ASP.NET中正确发布formcollection?_Asp.net_Asp.net Mvc_Model View Controller - Fatal编程技术网

如何在ASP.NET中正确发布formcollection?

如何在ASP.NET中正确发布formcollection?,asp.net,asp.net-mvc,model-view-controller,Asp.net,Asp.net Mvc,Model View Controller,我目前正在学习使用asp.net的mvc。但我在试图从控制器发布数据时遇到了问题 这是我的密码: [HttpPost] [ValidateInput(false)] public ActionResult Create(FormCollection collection) { PostCareersViewModel career = new PostCareersViewModel { Title = co

我目前正在学习使用asp.net的
mvc
。但我在试图从控制器发布数据时遇到了问题

这是我的密码:

   [HttpPost]
    [ValidateInput(false)]
    public ActionResult Create(FormCollection collection)
    {

        PostCareersViewModel career = new PostCareersViewModel
        {
            Title = collection["Title"],
            Description = collection["Description"],
            Photo = collection["Photo"],
            CareerStatus = int.Parse(collection["CareerStatus"]),
            JobDescription = collection["JobDescription"],
            Contact = collection["Contact"],
            MainImage = Encoding.ASCII.GetBytes(collection.Get("Photo"))
        };
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("Title", career.Title.ToString()),
            new KeyValuePair<string, string>("Description", career.Description.ToString()),
            new KeyValuePair<string, string>("Photo", career.Photo.ToString()),
            new KeyValuePair<string, string>("CareerStatus", career.CareerStatus.ToString()),
            new KeyValuePair<string, string>("JobDescription", career.JobDescription.ToString()),
            new KeyValuePair<string, string>("Contact",career.Contact.ToString()),
            new KeyValuePair<string, string>("MainImage",career.MainImage.ToString())
        });

        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(UrlAddressHelper.Base_Url);

                //var responseTask = client.PostAsync(PostCareerString, new FormUrlEncodedContent(
                //                                  collection.
                //                                      AllKeys.ToDictionary(
                //                                          k => k, v => collection[v])));
                var responseTask = client.PostAsync(PostCareerString, content);
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }

            ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
PostAsJson异步需要FormUrlEndcodedContent作为参数,PostAsync需要httpcontent作为参数。但是formurlendcoded内容与PostAsync完美结合,为什么FormUrlEndcodedContent不与PostAsync一起运行

但我无法转换
main图像
Encoding.ASCII.GetBytes,因为我不会将其作为文件存储到
api
中(实际上我不知道该方法是否可以上传文件)

有什么办法解决这个问题吗?我是否做了正确的事情,如将
FormCollection
转换为
model
转换为
FormUrlEncodedContent
(它仍然会给我400个请求)


我真的很感激贴出的每一个答案。提前感谢:)

请检查下面的图片和来自视图的数据

模型

此外,您的图像文件正在提交,这是您在视图中选择的

FormCollection

用于检查的示例视图渲染

请查一下密码

Cshtml页面代码


@使用(Html.BeginForm(“Create”、“postareers”、FormMethod.Post、new{@class=“bg light p-5 contact form”、enctype=“multipart/form data”}))
{
@Html.AntiForgeryToken()
公布新职位空缺

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.Title,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Title,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Title,“,new{@class=“text danger”}) @LabelFor(model=>model.Description,htmlAttributes:new{@class=“controllabel col-md-2”}) @text区域(model=>model.Description,new{htmlAttributes=new{@class=“form control”},id=“edit”}) @Html.ValidationMessageFor(model=>model.Description,“,new{@class=“text danger”}) @LabelFor(model=>model.Photo,htmlAttributes:new{@class=“controllabel col-md-2”}) @TextBox(“myphoto”,null,新的{type=“file”,占位符=Html.DisplayNameFor(model=>model.Photo),@class=“form control”}) @Html.ValidationMessageFor(model=>model.Photo,“,new{@class=“text danger”}) @*@EditorFor(model=>model.Photo,new{htmlAttributes=new{@class=“form control”})*@ @LabelFor(model=>model.CareerStatus,htmlAttributes:new{@class=“controllabel col-md-2”}) @DropDownList(“CareerStatus”,新的SelectList(ViewBag.CSListItem,“Value”,“Name”),新的{@class=“form control”}) @Html.ValidationMessageFor(model=>model.CareerStatus,“,new{@class=“text danger”}) @LabelFor(model=>model.JobDescription,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.JobDescription,new{htmlAttributes=new{@class=“form control”}}) @*@Html.ValidationMessageFor(model=>model.JobDescription,“,new{@class=“text danger”})*@ @LabelFor(model=>model.Contact,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Contact,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Contact,“,new{@class=“text danger”}) } @ActionLink(“返回列表”、“索引”)
用于测试数据的控制器代码是否在视图中

公共类PostCareerController:控制器
{
公共行动结果索引()
{
返回视图(新的PostCareerViewModel());
}
[HttpPost]
[验证输入(错误)]
公共操作结果创建(FormCollection集合、PostCareerViewModel模型、HttpPostedFileBase myphoto)
{
PostCareerViewModel职业=新的PostCareerViewModel
{
标题=集合[“标题”],
Description=集合[“Description”],
CareerStatus=int.Parse(集合[“CareerStatus”]),
JobDescription=集合[“JobDescription”],
联系人=集合[“联系人”],
};
如果(myphoto!=null)
{
string Path=Server.MapPath(string.Concat(“~/Upload/”,myphoto.FileName));
myphoto.SaveAs(路径);
career.Photo=string.Concat(Request.Url.Authority,“/Upload/”,myphoto.FileName);
}
var content=newformurlencodedcontent(new[]
{
新的KeyValuePair(“Title”,career.Title.ToString()),
新的KeyValuePair(“Description”,career.Description.ToString()),
新的KeyValuePair(“Photo”,career.Photo.ToString()),
新的KeyValuePair(“CareerStatus”,career.CareerStatus.ToString()),
新的KeyValuePair(“JobDescription”,career.JobDescription.ToString()),
新的KeyValuePair(“Contact”,career.Contact.ToString())
});
<section class="ftco-section">
    <div class="container">
        @using (Html.BeginForm("Create", "PostCareers", FormMethod.Post, new { @class = "bg-light p-5 contact-form" }))
        {
            @Html.AntiForgeryToken()

            <h4>Post New Job Vacancy</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.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" }, id = "edit" })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Photo, new { type = "file", placeholder = Html.DisplayNameFor(model => model.Photo), @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Photo, "", new { @class = "text-danger" })
                    @*@Html.EditorFor(model => model.Photo, new { htmlAttributes = new { @class = "form-control" } })*@
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CareerStatus, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("CareerStatus", new SelectList(ViewBag.CSListItem, "Value", "Name"), new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.CareerStatus, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.JobDescription, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.JobDescription, new { htmlAttributes = new { @class = "form-control" } })
                    @*@Html.ValidationMessageFor(model => model.JobDescription, "", new { @class = "text-danger" })*@
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-primary py-3 px-5" />
                </div>
            </div>
        }

        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
    </div>
</section>
var responseTask = client.PostAsync(PostCareerString, new FormUrlEncodedContent(
                                                      collection.
                                                         AllKeys.ToDictionary(
                                                            k => k, v => collection[v])));
<section class="ftco-section">
    <div class="container">
        @using (Html.BeginForm("Create", "PostCareers", FormMethod.Post, new { @class = "bg-light p-5 contact-form", enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()

            <h4>Post New Job Vacancy</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.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" }, id = "edit" })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBox("myphoto",null, new { type = "file", placeholder = Html.DisplayNameFor(model => model.Photo), @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Photo, "", new { @class = "text-danger" })
                    @*@Html.EditorFor(model => model.Photo, new { htmlAttributes = new { @class = "form-control" } })*@
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CareerStatus, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">                   
                    @Html.DropDownList("CareerStatus", new SelectList(ViewBag.CSListItem, "Value", "Name"), new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.CareerStatus, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.JobDescription, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.JobDescription, new { htmlAttributes = new { @class = "form-control" } })
                    @*@Html.ValidationMessageFor(model => model.JobDescription, "", new { @class = "text-danger" })*@
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-primary py-3 px-5" />
                </div>
            </div>
        }

        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
    </div>
</section>
public class PostCareersController : Controller
    {
        public ActionResult Index()
        {
            return View(new PostCareersViewModel());
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection, PostCareersViewModel model, HttpPostedFileBase myphoto)
        {

            PostCareersViewModel career = new PostCareersViewModel
            {
                Title = collection["Title"],
                Description = collection["Description"],
                CareerStatus = int.Parse(collection["CareerStatus"]),
                JobDescription = collection["JobDescription"],
                Contact = collection["Contact"],
            };
            if (myphoto != null)
            {
                string Path = Server.MapPath(string.Concat("~/Upload/", myphoto.FileName));
                myphoto.SaveAs(Path);
                career.Photo = string.Concat(Request.Url.Authority, "/Upload/", myphoto.FileName);
            }
            var content = new FormUrlEncodedContent(new[]
            {
            new KeyValuePair<string, string>("Title", career.Title.ToString()),
            new KeyValuePair<string, string>("Description", career.Description.ToString()),
            new KeyValuePair<string, string>("Photo", career.Photo.ToString()),
            new KeyValuePair<string, string>("CareerStatus", career.CareerStatus.ToString()),
            new KeyValuePair<string, string>("JobDescription", career.JobDescription.ToString()),
            new KeyValuePair<string, string>("Contact",career.Contact.ToString())
        });

            return RedirectToAction("Index");
        }
    }

    public class PostCareersViewModel
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Photo { get; set; }
        public int CareerStatus { get; set; }
        public string JobDescription { get; set; }
        public string Contact { get; set; }
    }