【问题标题】:Receive push messages and use content in MVC 4在 MVC 4 中接收推送消息并使用内容
【发布时间】:2014-06-09 10:06:41
【问题描述】:

我是 MVC 新手,我想创建一个 MVC4 Web Api,它接收带有请求正文中内容的推送消息 (HTTP Post) 并将其保存在数据库中。

现在我有这段代码(只需将内容传递给视图而不是保存在数据库中):

[HttpPost]
public ActionResult Index()
{
    string data;
    using (Stream receiveStream = Request.InputStream)
    {
        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
        {
        data = readStream.ReadToEnd();
        }
    }

    data = data.Split('\"')[1];

    //var x = data;
    ViewBag.Message = data;

    return View();
}

我的问题是如何强制控制器获取方法签名中的内容,例如,如果内容存在于名为 data 的参数中:

    public ActionResult Index(string data)

提前致谢

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 http-post


    【解决方案1】:

    您可以将数据绑定到Model,然后使用它,甚至可以简单地从视图中传递字符串

    代码示例 查看

    @model MVCFormsExample.ViewModels.BookViewModel
    
    @{
    ViewBag.Title = "Create Book";
    }
    
    
    @using (Html.BeginForm())
    {
    @Html.HiddenFor(m => m.Id)
    
    <div class="editor-label">
        @Html.LabelFor(m => m.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(m => m.Name)
    
    </div>
    
    <button type="submit">Create</button>
    }
    

    控制器

    `[HttpPost]
        public ActionResult Create(BookViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                // TODO: Save book
                return RedirectToAction("Index");
            }
    
            return View(viewModel);
        }'
    

    查看

    @using(Html.BeginForm("Show", "User", FormMethod.Post, new { uid = 1, uname = "user1" }))
    {
    <input type="submit" value="+"/>
    }
    

    控制器

    [HttpPost]
    public string Show(int? uid, string uname)
    {
    return uname + uid.ToString();
    }
    

    WEB API 你可以关注This Link

    【讨论】:

    • 谢谢,但是我从外包服务中获得了发布请求,而不是从视图中获得,所以我仍然需要阅读内容。我说的对吗?
    • 如果视图没有发送内容,我该如何将数据绑定到模型中?
    • 因为那个模型不会被使用我说你需要WEB API
    • 发布了相同的链接。
    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2019-06-28
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2014-08-15
    相关资源
    最近更新 更多