在post方法中从部分视图中检索值 [英] Retrieving values from partial view during post method

查看:208
本文介绍了在post方法中从部分视图中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含下拉列表的视图,并在下拉列表项目被选中时加载部分视图。当提交表单时,我希望能够在表单提交时从主视图和部分视图中获取值。
这里是主视图

  @model AdminPortal.Areas.Hardware.Models。 CreateModule 
@ {
ViewBag.Title =Create Module;
Layout =〜/ Views / shared / _BootstrapLayout.basic.cshtml;
}

@ Html.ValidationSummary(true)


< fieldset class =form-horizo​​ntal>
< legend>添加模块< small>创建< / small>< / legend>
@using(Html.BeginForm(CreateModule,Module,new {id =AddModuleForm}))
{
@ Html.ValidationSummary(true)
< ; div class =controls>
< div class =input-block-level> @ Html.TextBoxFor(model => model.ModuleId,new {@placeholder =ModuleID})< / div>
< br />
< div class =input-block-levelid =selectedModuleTypeName> @ Html.DropDownListFor(model => model.SelectedModuleTypeName,Model.TypeNames,Select Moduletype,new {id = ModuleList})< / DIV>

< br />
< div id =partialDiv>< / div>
< / div>
< div class =form-actionsid =buttons>
< button type =submitclass =btn btn-primaryid =Submit>保存更改< / button>
@ Html.ActionLink(Cancel,ModuleList,null,new {@class =btn})
< / div>

}

< / fieldset>
< div>
@ Html.ActionLink(返回列表,ModuleList)
< / div>
< script>
$(#buttons)。hide(); $(#ModuleList)。on(change,function(){
var modId = $(this).val();
$ .get('@ Url。 Action(GetModulePropertyName,Module)',{moduleTypeValue:modId},function(result){
$(#partialDiv)。html(result);
}); $ b $ (函数(){alert(done);})
.fail(function(){alert()(); //取消注释以下部分以检查部分视图是否正常工作。 失败);})
.always(function(){alert(completed);}); * /

});
$(#buttons)。show();

< / script>

这里是局部视图

  @model IEnumerable< string> 

@foreach(Model中的var名称)
{
< div class =input-block-level> @ Html.TextBoxFor(m => names, new {Value =,placeholder = names})< / div>
< br />

这是我的模型

  public class CreateModule 
{
//空表单处理表单序列化
public CreateModule()
{
}

[必需]
公共字符串ModuleId {get;组; }

[DataType(DataType.DateTime)]
public DateTime DateEntered {get;组; }

[必需]
公共字符串SelectedModuleTypeName {get;组; }
public IEnumerable< SelectListItem> TypeNames {get;组; }

公共列表<属性>属性{get;组; }
}

public class Property
{
public string Name {get;组; }
public string Value {get;组; } >

以下是方法脚本在主视图中转发到

  [HttpGet] 
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
var modulePropertyNames = _repository.GetModuleKindPropertyNames(moduleTypeValue);
返回PartialView(GetModulePropertyName,modulePropertyNames);
}

最后这里是主视图的 httppost方法

  [HttpPost] 
public ActionResult CreateModule(CreateModule moduleV)
{
var module = new Module
{
ModuleTypeId = Convert.ToInt64(moduleV.SelectedModuleTypeName),
ModuleId = moduleV.ModuleId,
DateEntered = moduleV.DateEntered,


};
if(ModelState.IsValid)
{
_repository.AddModule(module);
成功(Module added successfully!);
返回RedirectToAction(ModuleList,Module,new {area =Hardware});
}


错误(出错了!);
返回RedirectToAction(CreateModule,Module,new {area =Hardware});





$ p $目前情况

发布表单时,通过分部视图传递的模型的属性值为空。我得到了其他的值,比如typename,Module ID。

我想要的是什么:
我也想得到值通过局部视图传递的属性。 任何地方在你的形式。所以它将永远是空的。这很正常。



您可以继续操作。首先设置正确的导航属性,以便助手生成相应输入字段的正确名称。



还要确保您传递了 IEnumerable< ;

  model 模型为partial,如果您希望能够正确取回它们: [HttpGet] 
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
IList<属性> model = ...
return PartialView(GetModulePropertyName,model.ToList());
}

并在您的部分视图中使用编辑器模板:

  @model IList<属性> 
@ {
//这表示当前助手的导航上下文
ViewData.TemplateInfo.HtmlFieldPrefix =属性;


@ Html.EditorForModel()

和最后一步是为Property类定义一个自定义编辑器模板:〜/ Views / Shared / EditorTemplates / Property.cshtml (注意模板的名称和位置很重要)

  @model属性
< div class =input-block-level>
@ Html.HiddenFor(m => m.Name)
@ Html.TextBoxFor(m => m.Value,new {placeholder = Model.Name})
< / DIV>
< br />


I have a view which contains a dropdown list and on dropdownlist item being selected I load a partial view. And when the form is submitted I want to be able to get both the values from main view and partial view during form submit. Here is the main view

@model AdminPortal.Areas.Hardware.Models.CreateModule
@{
    ViewBag.Title = "Create Module";
    Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}

@Html.ValidationSummary(true)


<fieldset class="form-horizontal">
    <legend>Add a Module <small>Create</small></legend>
    @using (Html.BeginForm("CreateModule", "Module", new{id="AddModuleForm"}))
    {
        @Html.ValidationSummary(true)
        <div class ="controls">
            <div class="input-block-level">@Html.TextBoxFor(model => model.ModuleId, new {@placeholder = "ModuleID"})</div>
            <br/>
            <div class ="input-block-level" id="selectedModuleTypeName">@Html.DropDownListFor(model => model.SelectedModuleTypeName, Model.TypeNames,"Select Moduletype", new{id = "ModuleList"})</div>

            <br/>
            <div id="partialDiv"></div>
        </div>
         <div class="form-actions" id="buttons">
        <button type="submit" class="btn btn-primary" id="Submit">Save changes</button>
        @Html.ActionLink("Cancel", "ModuleList", null, new { @class = "btn " })
    </div>

    }

</fieldset>
<div>
    @Html.ActionLink("Back to List", "ModuleList")
</div>
<script>
    $("#buttons").hide();
    $("#ModuleList").on("change", function() {
        var modId = $(this).val();
        $.get('@Url.Action("GetModulePropertyName", "Module")', { moduleTypeValue: modId }, function(result) {
            $("#partialDiv").html(result);
        });
        //uncomment following section to check if the partial view is working properly
        /*.done(function() { alert("done"); })
            .fail(function() { alert("fail"); })
            .always(function() { alert("completed"); });*/

    });
        $("#buttons").show();

</script>

and here is the partial view

    @model IEnumerable<string>

    @foreach(var names in Model)
    {
        <div class="input-block-level">@Html.TextBoxFor(m=>names, new{Value="", placeholder=names})</div>
        <br/>
    }

Here is my model

public class CreateModule
    {
        //Empty form to handle form serialization
        public CreateModule()
        {
        }

        [Required]
        public string ModuleId { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime DateEntered { get; set; }

        [Required]
        public string SelectedModuleTypeName { get; set; }
        public IEnumerable<SelectListItem> TypeNames { get; set; }

        public List<Property> Properties { get; set; }
    }

public class Property
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }

Here is the method that script in main view forwards to

[HttpGet]
        public ActionResult GetModulePropertyName(string moduleTypeValue)
        {
            var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
            var modulePropertyNames = _repository.GetModuleKindPropertyNames(moduleTypeValue);
            return PartialView("GetModulePropertyName",modulePropertyNames);
        }

and finally here is httppost method for the main view

[HttpPost]
        public ActionResult CreateModule(CreateModule moduleV)
        {
            var module = new Module
                {
                    ModuleTypeId = Convert.ToInt64(moduleV.SelectedModuleTypeName),
                    ModuleId = moduleV.ModuleId,
                    DateEntered = moduleV.DateEntered,


                };
            if (ModelState.IsValid)
            {
               _repository.AddModule(module);
                Success("Module added successfully!");
                return RedirectToAction("ModuleList", "Module", new {area = "Hardware"});
            }


                Error("Something went wrong!");
                return RedirectToAction("CreateModule", "Module", new { area = "Hardware" });

        }

Current situation: When the form is posted, the properties value of the model that is being passed via partial view is null. I get other values, like typename, Module ID.

What I'd want: I also want to get the value of properties that is being passed via partial view.

解决方案

You don't have any input field for the Properties property anywhere in your form. So it will always be null. That's normal.

Here's how you could proceed. Start by setting the correct navigational property so that the helper generates correct names of the corresponding input fields.

Also make sure that you are passing an IEnumerable<Property> model to the partial if you want to be able to get them back correctly:

[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
    var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
    IList<Property> model = ...
    return PartialView("GetModulePropertyName", model.ToList());
}

and in your partial view use an editor template:

@model IList<Property>
@{
    // This indicates the current navigational context to the helpers
    ViewData.TemplateInfo.HtmlFieldPrefix = "Properties";
}

@Html.EditorForModel()

and the last step is to define a custom editor template for the Property class: ~/Views/Shared/EditorTemplates/Property.cshtml (note that the name and location of the template is important)

@model Property
<div class="input-block-level">
    @Html.HiddenFor(m => m.Name)
    @Html.TextBoxFor(m => m.Value, new { placeholder = Model.Name })
</div>
<br />

这篇关于在post方法中从部分视图中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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