保存模型,在模型 [英] Saving a model within a model

查看:118
本文介绍了保存模型,在模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个由 ID 名称属性类code>和数据类型
数据类型已填充了静态值,而被用作一个下拉列表中。



现在,当用户从列表中选取一定值时,列表值是准确的,应用程序打开附加的文本框和按钮,用于填充该列表。



模式是这样的。



属性模型

 公共类属性
{
公众诠释ID {搞定;设置;}
公共字符串名称{;设置;}

公众诠释DTypeID {搞定;设置;}
公共虚拟D型DTypes {搞定;设置;}
}



列表模型



 公共类DLIST 
{
公众诠释ID {搞定;设置;}
公众诠释物业ID {搞定;设置;}
公共字符串ListValue {搞定;设置;}
}

这是我到目前为止已经完成

  @using(Html.BeginForm()){
@ Html.ValidationSummary(真)
<&字段集GT ;
< D​​IV CLASS =标签tablerow的>
< D​​IV CLASS =编辑器标签的TableCell>
< P>
名称
< / P>
< P>
数据类型
< / P>
< / DIV>
< D​​IV CLASS =主编场的TableCell>
< P>
@ Html.TextBoxFor(型号=> model.Name,新{@class =TEXTENTRY})
@ Html.ValidationMessageFor(型号=> model.Name)
< /差异无显着
< P>
@ Html.DropDownList(DTypeID(的SelectList)ViewBag.DTypeID,新{@class =下拉菜单,@onchange =DropDownChange()})
@ Html.ValidationMessageFor(型号= > model.DTypeID)
< / p>
< / DIV>
< / DIV>


< D​​IV ID =StaticListUI级=invis>
< D​​IV CLASS =标签tablerow的>
< D​​IV CLASS =编辑器标签的TableCell>
< P>
@ *这里去列表* @
< / P>
< / DIV>
< D​​IV CLASS =主编场的TableCell>
< P>
@ *在这里不用文本* @
@ Html.TextBox(textboxList)
< / P>
< P>
@ *在这里不用按钮* @
<按钮名称=按钮值=添加>添加< /按钮>
< / P>
< / DIV>

< / DIV>

< / DIV>


< p =类标签>
@ *<输入类型=提交值=创建/> * @
<按钮名称=按钮值=创造>创建< /按钮> |
<输入类型=按钮值=返回的onClick =JavaScript的:location.href =@ Url.Action(指数,财产);/>
< / P>
< /字段集>
}



因此​​,为了捕捉点击该按钮,我这样做是为了我的控制器。

  [HttpPost] 
公众的ActionResult创建(字符串键,字符串textboxList,房产物业)
{

如果(按钮==加)
{
VAR lastProperty = db.Properties.OrderByDescending(p => p.PropertyID).FirstOrDefault();
INT PROPID;
如果(lastProperty == NULL)
{
PROPID = 1;
}
,否则
{
PROPID = 1 + lastProperty.PropertyID;
}

DLIST DLIST =新DLIST();

dList.PropertyID = PROPID;
dList.ListValue = textboxList;

db.DLi​​sts.Add(DLIST);

返回查看(财产);
}

线专案编号= System.Web.HttpContext.Current.Session [_ SelectedProjectID]的ToString()。
INT PROJID = Convert.ToInt32(专案编号);
property.ProjectID = PROJID;
property.DateCreated = DateTime.Now;
property.DateEdited = DateTime.Now;

如果(ModelState.IsValid)
{
db.Properties.Add(财产);
db.SaveChanges();
返回RedirectToAction(「指数」);
}

ViewBag.DTypeID =新的SelectList(db.DType,ID,姓名,property.DTypeID);
返回查看(财产);
}

和问题是,当我点击添加按钮,它仍然为发送 ModelState.IsValid ,它不应该。我做了什么错了,还是我做任何事情的权利:(



注:其他一切基本工作原理



修改



所以,我改变了控制器接受参数从单击按钮不同,但还是缺了点什么......

  [ActionName(创建)] 
的[AcceptVerbs(HttpVerbs.Post)
[AcceptParameter(名称= 按钮,值=增加)]
公众的ActionResult Create_Add(字符串textboxList)
{
VAR lastProperty = db.Properties.OrderByDescending(p => p.PropertyID).FirstOrDefault ();
INT PROPID;
如果(lastProperty == NULL)
{
PROPID = 1;
}
,否则
$ { b $ b PROPID = 1 + lastProperty.PropertyID;
}

DLIST DLIST =新DLIST();

dList.PropertyID = PROPID;
dList.ListValue = textboxList;

db.DLi​​sts.Add(DLIST);
db.SaveChanges();



返回查看();
}

的[AcceptVerbs(HttpVerbs.Post)
[AcceptParameter(NAME =按钮值=创造)]
公众的ActionResult创建(物业。属性)
{
线专案编号= System.Web.HttpContext.Current.Session [_ SelectedProjectID]的ToString();
INT PROJID = Convert.ToInt32(专案编号);
property.ProjectID = PROJID;
property.DateCreated = DateTime.Now;
property.DateEdited = DateTime.Now;

如果(ModelState.IsValid)
{
db.Properties.Add(财产);
db.SaveChanges();
返回RedirectToAction(「指数」);
}

ViewBag.DTypeID =新的SelectList(db.DType,ID,姓名,property.DTypeID);
返回查看(财产);
}


公共类AcceptParameterAttribute:ActionMethodSelectorAttribute
{
公共字符串名称{;组; }
公共字符串值{获得;组; }

公众覆盖布尔IsValidForRequest(ControllerContext controllerContext,System.Reflection.MethodInfo的MethodInfo)
{
VAR REQ = controllerContext.RequestContext.HttpContext.Request;
返回req.Form [this.Name] == THIS.VALUE;
}
}


解决方案

您有 db.DLi​​sts.Add(DLIST); 但千万不要把它保存在数据库中,你可以返回视图。你可以把 db.Configuration.ValidateOnSaveEnabled = FALSE; 上方 db.DLi​​sts.Add(DLIST); 看如果该作品,但我想应该是这样的:

  db.Configuration.ValidateOnSaveEnabled = FALSE; 
db.DLi​​sts.Add(DLIST);
db.SaveChanges();
返回查看(财产);

您可能要返回前关闭验证在救回来的。



更新
也许你可以试试这个:

  @ {
VAR textBoxData = form.find(输入[名称=textboxList])VAL()。
}
<输入类型=按钮值=添加称号=添加的onclick =location.href ='@ Url.Action(Create_Add,控制器,新{ textboxList = textBoxData})/>


So, I have this Property class that is defined by ID Name and DataType. DataType is already populated with static values, and is being used as a drop down list.

Now when a user picks certain value from the list, List value to be precise, application opens additional textbox and button, for populating that list.

Models go like this.

Property model

public class Property
{
    public int ID {get; set;}
    public string Name {get; set;}

    public int DTypeID {get; set;}
    public virtual DType DTypes {get; set;}
}

List model

public class DList
{
    public int ID {get; set;}
    public int PropertyID {get; set;}
    public string ListValue {get; set;}
}

And this is what I've done so far.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <div class="labels tableRow">
            <div class="editor-label tableCell">
                <p>
                    Name
                </p>
                <p>
                    Data Type
                </p>
            </div>
            <div class="editor-field tableCell">
                <p>
                    @Html.TextBoxFor(model => model.Name, new { @class = "textEntry" })
                    @Html.ValidationMessageFor(model => model.Name)
                </p>
                <p>
                    @Html.DropDownList("DTypeID", (SelectList)ViewBag.DTypeID, new { @class = "dropdown", @onchange = "DropDownChange()"})
                    @Html.ValidationMessageFor(model => model.DTypeID)
                </p>
            </div>
        </div>


        <div id="StaticListUI" class="invis">
            <div class="labels tableRow">
                <div class="editor-label tableCell">
                    <p>
                        @*here goes list*@
                    </p>
                </div>
                <div class="editor-field tableCell">
                    <p>
                        @*here goes textbox*@
                        @Html.TextBox("textboxList")
                    </p>
                    <p>
                        @*here goes button*@
                        <button name="button" value="add">Add</button>
                    </p>
                </div>

            </div>

        </div>


        <p class="labels">
            @*<input type="submit" value="Create" />*@
            <button name="button" value="create">Create</button> |
            <input type="button" value="Back" onClick='javascript:location.href = "@Url.Action("Index", "Property")";' />
        </p>
    </fieldset>
}

So in order to capture which button is clicked I did this for my controller.

[HttpPost]
public ActionResult Create(string button, string textboxList, Property property)
{

    if (button == "add")
    {
        var lastProperty = db.Properties.OrderByDescending(p => p.PropertyID).FirstOrDefault();
        int propID;
        if (lastProperty == null)
        {
            propID = 1;
        }
        else
        {
            propID = 1 + lastProperty.PropertyID;
        }

        DList dList = new DList();

        dList.PropertyID = propID;
        dList.ListValue = textboxList;

        db.DLists.Add(dList);

        return View(property);
    }

    string projectID = System.Web.HttpContext.Current.Session["_SelectedProjectID"].ToString();
    int projID = Convert.ToInt32(projectID);
    property.ProjectID = projID;
    property.DateCreated = DateTime.Now;
    property.DateEdited = DateTime.Now;

    if (ModelState.IsValid)
    {
        db.Properties.Add(property);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.DTypeID = new SelectList(db.DType, "ID", "Name", property.DTypeID);
    return View(property);
}

And the problem is that when I click Add button, it still sends a check for ModelState.IsValid, which shouldn't. What have I done wrong, or have I done anything right :(

Note: Everything else basically works.

EDIT

So I've altered the controller to accept parameters from button clicked differently. But still something is missing...

    [ActionName("Create")]
    [AcceptVerbs(HttpVerbs.Post)]
    [AcceptParameter(Name = "button", Value = "add")]
    public ActionResult Create_Add(string textboxList)
    {
        var lastProperty = db.Properties.OrderByDescending(p => p.PropertyID).FirstOrDefault();
        int propID;
        if (lastProperty == null)
        {
            propID = 1;
        }
        else
        {
            propID = 1 + lastProperty.PropertyID;
        }

        DList dList = new DList();

        dList.PropertyID = propID;
        dList.ListValue = textboxList;

        db.DLists.Add(dList);
        db.SaveChanges();



        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [AcceptParameter(Name="button", Value="create")]
    public ActionResult Create(Property property)
    {
        string projectID = System.Web.HttpContext.Current.Session["_SelectedProjectID"].ToString();
        int projID = Convert.ToInt32(projectID);
        property.ProjectID = projID;
        property.DateCreated = DateTime.Now;
        property.DateEdited = DateTime.Now;

        if (ModelState.IsValid)
        {
            db.Properties.Add(property);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.DTypeID = new SelectList(db.DType, "ID", "Name", property.DTypeID);
        return View(property);
    }


    public class AcceptParameterAttribute : ActionMethodSelectorAttribute
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            var req = controllerContext.RequestContext.HttpContext.Request;
            return req.Form[this.Name] == this.Value;
        }
    }

解决方案

You have db.DLists.Add(dList); but do don't save it in the database, you just return the view. You could put db.Configuration.ValidateOnSaveEnabled = false; above the db.DLists.Add(dList); and see if that works, however I think it should look like this:

db.Configuration.ValidateOnSaveEnabled = false;
db.DLists.Add(dList);
db.SaveChanges();
return View(property);

You may want to turn the Validate On Save back on before the return.

Update Perhaps you could try this:

@{
    var textBoxData = form.find('input[name="textboxList"]').val();
}
<input type="button" value="Add"  title="Add"  onclick="location.href='@Url.Action("Create_Add", "Controller", new { textboxList = textBoxData })'" />

这篇关于保存模型,在模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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