MVC模型属性发布表单上无效 [英] MVC model property null on posting form

查看:129
本文介绍了MVC模型属性发布表单上无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个MVC 4应用程序,我在submiting使用强大的视图模型形式问题。

我打电话的地方在GET的ActionResult我宣布一个模型实例,并把它传递给局部视图和存储在隐藏字段的字段的局部视图。
调试时我看到所有的领域越来越价值观和正常工作。

在用户提交表单后,我用用户填写这个模特属性加的属性。

问题是,调用POST操作的结果时,要列出越来越空。

该控制器:

  [HTTPGET]
    公众的ActionResult MessageDetails(字符串ID)
    {
        MessageModel米;
        字符串userfullname =的String.Empty;        ServiceReference2.WebService1Soap WS =新ServiceReference2.WebService1SoapClient();
        数据表DT = ws.GetMessageDetails(bcce7f7ad7596f963f4adb23d713e0d4,329392de8a55edf86c0881a57381cbe6,编号User.Identity.Name).Tables [0];        如果(会话[用户]!= NULL)
            userfullname = ((HaifanetMobile.Models.LoginModel)Session[\"user\"]).LoginDS.Tables[0].Rows[0][((HaifanetMobile.Models.LoginModel)Session[\"user\"]).LoginDS.Tables[0].Columns[\"fullname\"].Ordinal].ToString();        M =新MessageModel(DT,User.Identity.Name,userfullname);        返回PartialView(MessageDetails,米);
    }
    [HttpPost]
    公众的ActionResult ReplyMessage(MessageModel模型)
    {     //这里的地方列出越来越空
        变种误差= ModelState.Values​​.SelectMany(V => v.Errors);
        如果(ModelState.IsValid)
        {            model.Send();
            返回的内容(成功);
        }
        返回PartialView(MessageDetails模型);
    }

视图:

  @model HaifanetMobile.Models.MessageModel<脚本类型=文/ JavaScript的>
    功能showMessagesPanel1(){        $('#messagedetails_panel')切换()。
        $(#messages_panel)显示()。
    }
    $(函数(){
        $('形式')。提交(函数(){            $ .validator.unobtrusive.parse($('形式')); //添加            如果($(本).valid()){
                $阿贾克斯({
                    网址:this.action,
                    类型:this.method,
                    数据:$(本).serialize()
                    成功:函数(结果){
                        警报(信息已发出);                    },
                    错误:函数(){
                        警报(错误);
                    }
                });
            }
            返回false;
        });
    });
< / SCRIPT>
    <表ID =messages_panel_mbar的cellpadding =0CELLSPACING =0>    &所述; TR>
        < TD类=left_mbar>        < / TD>
        < TD类=main_mbar>
        < / TD>
        < TD ID =back_msg_details级=right_mbar>< / TD>
    < / TR>
< /表>
    < D​​IV的风格=高度:10%;宽度:100%;字体:黑体;字体大小:20像素;文本对齐:权利;> @ Html.Raw(Model.Subject)LT; / DIV>
    < D​​IV ID =msg_chat的风格=文本对齐:权利;宽度:100%;高度:汽车;最大高度:80%;溢出-Y:滚动;>
          @ Html.Raw(Model.MsgHistory)
    < / DIV>
    < D​​IV ID =reply_msg的风格=高度:5%>答复和LT; / DIV>    < D​​IV ID =reply_msg_block级=看得见的风格=宽度:100%;高:45%;>        @using(Ajax.BeginForm(ReplyMessage,SettingsMenu,空,新AjaxOptions {},{新@class =center_form}))
        {
            @ Html.ValidationSummary(真的,);
            <字段集的风格=高度:75%>                @ Html.Hidden(主题,Model.Subject)
                @ Html.Hidden(的ParentId,Model.ParentId)
                @ Html.Hidden(发件人,Model.From)
                @ Html.Hidden(fullnamesender,Model.fullnamesender)
                @ Html.Hidden(收件人,Model.To)
                < D​​IV ID =textarea_msg_reply>
                        @ Html.TextAreaFor(M = GT; m.Content,新{@class =})
                        @ Html.ValidationMessageFor(M = GT; m.Content)
                < / DIV>            < /字段集>            <输入类型=提交值=发送/>
        }    < / DIV>

模型:

 公共类MessageModel
    {
        公共字符串从{搞定;组; }        [必需(的ErrorMessage =输入到)]
        公开名单<联系与GT;要得到;组; }        [必需(的ErrorMessage =输入主题)]
        [StringLength(100的ErrorMessage =最大1000字符)]
        公共字符串主题{搞定;组;}        [StringLength(1000,的ErrorMessage =最大1000字符)]
        公共字符串内容{搞定;组; }        公共字符串MsgHistory {搞定;组; }        公共字符串fullnamesender {搞定;组; }        公共字符串的ParentId {搞定;组; }        公众的DateTime LastMsgDate {搞定;组; }        公共BOOL readed = FALSE;
} //我省略了构造....


解决方案

看看这个问题,答案。

<一个href=\"http://stackoverflow.com/questions/10400551/using-asp-net-and-mvc-3-how-can-i-create-hidden-fields-so-that-a-list-with-an-a\">Using ASP.NET MVC和3,我怎样才能创建隐藏字段,以便使用数组作为列表中的每个项目的值列表正确结合?

HiddenFor通常更易于使用,但它不会自己解决问题。您应该将隐藏你想回发后使用每个列表项的每个属性。

然而,我不建议这种方法。您应该只把一个隐藏字段的原始邮件的标识,并回传后,查看收件人列表。

I'm developing a MVC 4 application and I'm having problem submiting a form using strong view model.

I'm calling a partial view where in the GET actionResult I declare a model instance and passing it to the partial view and store the fields in hidden fields. When debugging I see that all field are getting values and it works fine.

After the user submits the form, I use this model properties plus the properties filled by the user.

The problem is that the To list is getting null when calling the post action result.

The controllers:

   [HttpGet]
    public ActionResult MessageDetails(string id)
    {
        MessageModel m;
        string userfullname =  String.Empty;

        ServiceReference2.WebService1Soap ws = new ServiceReference2.WebService1SoapClient();
        DataTable dt = ws.GetMessageDetails("bcce7f7ad7596f963f4adb23d713e0d4", "329392de8a55edf86c0881a57381cbe6",id,User.Identity.Name).Tables[0];

        if (Session["user"] != null)
            userfullname = ((HaifanetMobile.Models.LoginModel)Session["user"]).LoginDS.Tables[0].Rows[0][((HaifanetMobile.Models.LoginModel)Session["user"]).LoginDS.Tables[0].Columns["fullname"].Ordinal].ToString();

        m = new MessageModel(dt, User.Identity.Name, userfullname);



        return PartialView("MessageDetails",m);
    }


    [HttpPost]
    public ActionResult ReplyMessage(MessageModel model)
    {

     // here's where the To list is getting empty
        var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {

            model.Send();
            return Content("Success");
        }


        return PartialView("MessageDetails",model);
    }

The view:

@model HaifanetMobile.Models.MessageModel

<script type="text/javascript">
    function showMessagesPanel1() {

        $('#messagedetails_panel').toggle();
        $("#messages_panel").show();
    }


    $(function () {
        $('form').submit(function () {

            $.validator.unobtrusive.parse($('form'));  //added

            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        alert("Message Sent");

                    },
                    error: function () {
                        alert("Error");
                    }
                });
            }
            return false;
        });
    });
</script>




    <table id="messages_panel_mbar" cellpadding="0" cellspacing="0">

    <tr>
        <td class="left_mbar">

        </td>
        <td class="main_mbar"> 
        </td>
        <td id="back_msg_details" class="right_mbar"></td>
    </tr>
</table>


    <div style="height:10%; width:100%; font: bold; font-size: 20px; text-align:right;"> @Html.Raw(Model.Subject)</div>
    <div id="msg_chat" style="text-align:right; width:100%; height:auto; max-height:80%; overflow-y:scroll;">
          @Html.Raw(Model.MsgHistory)
    </div>
    <div id="reply_msg" style="height: 5%">reply</div>

    <div id="reply_msg_block" class="visible" style="width:100%; height:45%;">

        @using (Ajax.BeginForm("ReplyMessage", "SettingsMenu", null, new AjaxOptions { }, new { @class = "center_form" }))
        {


            @Html.ValidationSummary(true, "");


            <fieldset style="height:75%">



                @Html.Hidden("Subject", Model.Subject)
                @Html.Hidden("ParentId", Model.ParentId)
                @Html.Hidden("From", Model.From)
                @Html.Hidden("fullnamesender", Model.fullnamesender)
                @Html.Hidden("To", Model.To)


                <div id="textarea_msg_reply">
                        @Html.TextAreaFor(m => m.Content, new { @class = "" })
                        @Html.ValidationMessageFor(m => m.Content)
                </div>

            </fieldset>

            <input type="submit" value="send" />


        }

    </div>

The model:

 public class MessageModel
    {
        public string From { get; set; }

        [Required(ErrorMessage = "Enter To")]
        public List<Contact> To { get; set; }

        [Required(ErrorMessage = "Enter Subject")]
        [StringLength(100, ErrorMessage = "Max 1000 chars")]
        public string Subject {get; set;}

        [StringLength(1000, ErrorMessage = "Max 1000 chars")]
        public string Content { get; set; }

        public string MsgHistory { get; set; }

        public string fullnamesender { get; set; }

        public string ParentId { get; set; }

        public DateTime LastMsgDate { get; set; }

        public bool readed = false;


} // I omitted the constructors....

解决方案

Take a look at this question and the answer.

Using ASP.NET and MVC 3, how can I create hidden fields so that a List with an array as a value of each item in the list binds correctly?

HiddenFor is generally easier to use, but it won't solve your problem by itself. You should place a hidden for every property of every list item you want to use after postback.

However, I would not recommend this approach. You should only place a hidden field for the identifier of the original message, and look up the recipient list after postback.

这篇关于MVC模型属性发布表单上无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆