在asp.net mvc

时间:2016-04-25 19:56:16

标签: asp.net-mvc

我有一个表单,有不同的输入字段,用户可以输入他们的信息 在表单内部,我有2个按钮。当用户单击一个名为“添加地址”的按钮时,我想用地址填充一个div。当用户点击其他名为“预览”的按钮时,表单将被验证并准备好用于预览页面。

以下是“我的地址”按钮在Index.cshtml中的定义

<button id ="address" class="btn btn-default" onclick="location.href='@Url.Action("populateAddress","Information")?addressID=2222'">
      Add Address
</button>

因此,当用户点击添加地址时,我想填写我在Index.cshtml上的div中从数据库中检索的地址。下面是我想要显示检索地址的地方:

  <div class="row">
      <div class="col-md-1"></div>
      <div class="col-md-3">
          @Html.Label("Address", htmlAttributes: new { @class = "control-label" })
      </div>
      <div class="col-md-6">
          @ViewBag.FeedAddress      //Here I want to display my retrieved address
      </div>
  </div>  

因此,在按钮单击时,我调用我的'信息'控制器方法'populateAddress'并将addressID参数'2222'传递给它。

以下是我在控制器中定义'populateAddress'方法的方法:

public void populateAddress(string addressID = null)
        {
            var addressDetail = db.Agency.Where(e => e.AddressCode == addressID).ToList();
            string AddressRetrieved= "";
            string StreetAddress, City, State, Zip = "";

            foreach(var detail in addressDetail )
            {
                StreetAddress = detail.Address;
                City = detail.City;
                State = detail.State;
                Zip = detail.Zip;

                AddressRetrieved= StreetAddress + Environment.NewLine + City + ", " + State + " - " + Zip;    

            }
            ViewBag.FeedAddress =  AddressRetrieved
       }

所以,在这里,我的ViewBag充满了我检索到的地址 但是,我的问题是,在它填满地址之后,而不是在div中的Index.cshtml页面上显示它,而不是从ViewBag中检索值,我的页面将被提交并显示我的验证。

我想要的是,一旦用户填写“添加地址”按钮上方的部分表单并点击“添加地址”按钮,我的地址就会从ViewBag中检索出来,显示在div中,用户继续填写表格的其余部分。

我无法得到这种行为。

任何人都可以帮助我实现这种行为,或者可以告诉我缺少什么。谢谢!

编辑:

请找到Index.cshtml代码。页面很长,所以我只是添加了所需的代码:

// input fields for user
    <div class="form-group">
        <div class="col-md-2">
            @Html.Label("Title", htmlAttributes: new { @class = "control-label" })            </div>
        <div class="col-md-6">
            @Html.EditorFor((e => e.Title), new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>  

     //Add Address button
    <button id ="address" class="btn btn-default" onclick="location.href='@Url.Action("populateAddress","Information")?addressID=2222'">
      Add Address
    </button>

  //section to display retrieved address
 <div class="row">
      <div class="col-md-1"></div>
      <div class="col-md-3">
          @Html.Label("Address", htmlAttributes: new { @class = "control-label" })
      </div>
      <div class="col-md-6">
          @ViewBag.FeedAddress      //Here I want to display my retrieved address
      </div>
  </div>    

   // input fields for user
    <div class="form-group">
        <div class="col-md-2">
            @Html.Label("Description", htmlAttributes: new { @class = "control-label" })            </div>
        <div class="col-md-6">
            @Html.EditorFor((e => e.Description), new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>  


  //Preview Button  
  <div class="form-group">
        <div class="col-md-offset-2 col-md-6">
            <input type="submit" value="Preview" class="btn btn-default" />
        </div>
    </div>

1 个答案:

答案 0 :(得分:1)

在控制器中(本例中名为mainController):

public JsonResult GetAddress(int addressId)
{
    // do whatever to get what you need
    // the Address model will need to be JSON serialized
    return JSON(Address);
}

在javascript中:

function GetAddress(addressId)
{
    $.ajax({
        type: "GET",
        async: false,
        url: "/main/GetAddress?addressId=" + addressId
        contentType: "application/json",
        context: this,
        success: function (data) {
            console.log(data);
            // do stuff here
        },            
        error: function (error) {
            alert("error");
        }
    });    
}

重要路线信息:
网址是&#34; / main / GetAddress /&#34;这意味着它将路由到控制器mainController(注意&#39; main&#39;部分匹配),控制器内部的函数是GetAddress。这是一个&#34; GET&#34;请求所以使用url变量很好。

这是你用MVC进行ajax调用的基本结构。

特别说明:在控制器方法中,你返回一个JsonResult,而不是一个ActionResult!当您尝试通过View进行路由并让Razor引擎创建HTML标记时,请使用ActionResult。但是如果你刚刚返回JSON,请使用JsonResult。

编辑: 如果你想做一个POST而不是GET,这就是它的样子: 在控制器中:

public JsonResult PostSomething(MyClass data)
{
    // do something with the data -- class is MyClass
    var result = ...... // whatever the result is, Null is ok I'd recommend some sort of "successful" reply
    return JSON(result);
}

在javascript中:

function SubmitForm()
{
    var formData;
    // common to use jQuery to get data from form inputs

    // use JSON.stringify to serialize the object
    var data = JSON.stringify(formData);

    // the ajax is almost the same, just add one data: field
    $.ajax({
         type: "POST",
         url: "/main/PostSomething"
         contentType: "application/json",
         data: data,    // the second 'data' is your local variable
         success: function(data){
              console.log(data);
         },
         error: function(error){
              alert(error)
        }
    });
}

&#39; asynch:false&#39;和&#39;背景:这个&#39;从第一个例子开始实际上并不需要(大部分时间)。

与大多数编程一样,有多种方法可以实现。这些示例只是简单(但相当标准)的片段,可以让您走上正确的轨道。