MVC3 ViewBag概念

时间:2012-06-29 08:58:48

标签: asp.net-mvc-3

这是View ViewPage.cshtml

 @using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
<div>Name:<a>@ViewBag.st</a><br /></div>
        <input type="submit" value="Submit" /> 
<br />
}

我的jquery用于编辑@ ViewBag.st

    <script type="text/javascript">
  $(document).ready(function () {
    $('a').click(function () {
        var textbox = $('<input id="Text1" type="text" size="100"  />')
        var oldText = $(this).text();
        $(this).replaceWith(textbox);
        textbox.blur(function () {
            var newValue = $(this).val();
            $(this).replaceWith($('<a>' + newValue + '</a>'));
        });
        textbox.val(oldText);
    });


});

</script>

我的控制器方法是

public ActionResult Viewdetails()
    {
        User ur = new User();
        ur.Name = "Danny";

        ViewBag.st = ur.Name;
        return View();

    }

我的模型类是 User.cs

 public class User
{

    //public string name { get; set; }
private string m_name = string.Empty;

public string Name
{
    get
    {
        return m_name;
    }
    set
    {
        m_name = value;
    }
}
}

在编辑@ ViewBag.title之后我想存储该值并传递给下一个视图任何人都可以建议一些想法

1 个答案:

答案 0 :(得分:2)

我建议你根本不要使用ViewBag

因此,在您的javascript中,您可以为文本框指定与User模型属性(Name)相同的名称:

var textbox = $('<input type="text" size="100" name="Name" />');

然后进行2个控制器操作(GET和POST):

public ActionResult Viewdetails()
{
    User ur = new User();
    ur.Name = "Danny";
    return View(ur);
}

[HttpPost]
public ActionResult Display(User model)
{
    return View(model);
}

Viewdetails.cshtml内:

@model User
@using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
    <div>Name: <a>@Model.Name</a><br /></div>
    <input type="submit" value="Submit" /> 
    <br />
}

Display.cshtml

@model User
<div>You have selected: @Model.Name</div>