0

I have a form, with different input fields, where user can enter their information.
Inside of the form, I have 2 buttons. When user clicks one button called 'Add address', I want to fill up a div with the address. And when user clicks other button called 'Preview', the form is validated and prepared for preview page.

Below is how 'My Adrress' button is defined in Index.cshtml

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

So, when user clicks, Add Address, I want to fill up the address that I am retrieving from database in the div on Index.cshtml. Below is where I want to display the 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>  

So, on button click, I am calling my 'Information' controller method 'populateAddress' and passing the addressID parameter '2222' to it.

Below is how I am defining my 'populateAddress' method in my controller:

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
       }

So, here, my ViewBag is getting filled with my retrieved address.
But, my issue is, after it gets filled with the address, instead of showing it on my Index.cshtml page in the div where I am retrieving back the value from ViewBag, my page is instead getting submitted and showing my validations.

I want that, once user fills up part of the form above 'Add Address' button and clicks 'Add Address' button, my address is retrieved from ViewBag, shown inside the div and user proceed filling up the rest of the form.

I am unable to get this kind of behavior.

Can anyone please help me to achieve that behavior or may be tell what I am missing. Thanks!

EDIT:

Please find Index.cshtml code. The page is long, so I am just adding required code:

// 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>
6
  • can you share the complete code snippet of the Index.cshtml page including the submit button and etc.. ? Commented Apr 25, 2016 at 20:12
  • @Sampath : I just edited my post to show Index.cshtml. Commented Apr 25, 2016 at 20:23
  • First problem is onclick="location.href=..." Use AJAX to call the controller and then populate the form based on the result. Commented Apr 25, 2016 at 20:25
  • @nurdyguy - I am fairly new to MVC and AJAX. If you can please provide a sample code, that will be really helpful. Thanks! Commented Apr 25, 2016 at 20:28
  • 1
    This page has some good info: chsakell.com/2013/05/10/ajax-and-jquery-in-asp-net-mvc I'll see if I can code up a simple example for you as well. Commented Apr 25, 2016 at 20:32

1 Answer 1

1

In the controller (named mainController for this example):

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

In the 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");
        }
    });    
}

Important routing info:
The url is "/main/GetAddress/" which means it will route to the controller mainController (notice the 'main' part matches) and the function inside the controller is GetAddress. It is a "GET" request so using the url variable is fine.

This is the basic structure of how you do an ajax call with MVC.

Special note: In the controller method you return a JsonResult, NOT an ActionResult! Use ActionResult when you are trying to route through a View and have the Razor engine create the HTML markup. But if you are just returning JSON, use JsonResult.

EDIT: In case you want to do a POST instead of a GET, here is what it would look like: In the controller:

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);
}

In the 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)
        }
    });
}

The 'asynch: false' and 'context: this' from the first example are actually not necessary in either (most of the time).

As with most of programming, there is more than one way to do it. These examples are just simple (but fairly standard) snippets to get you on the right track.

Sign up to request clarification or add additional context in comments.

12 Comments

Thank you so much. I have been trying to achieve this for hours. Thanks for the link you referred and for your sample code. It worked. Thanks again! :)
Glad it worked for you. I'm going to add an edit addressing what to do if it is a POST instead of a GET for when you run in to that.
I have an additional question here. Is there a way I can assign value to a model property in Index.cshtml on 'Add address' button click? Thanks in advance!
I'm not sure what you mean. Do you mean after the ajax returns or when the page initially loads?
Not sure if this addresses your question but here is the basic flow of C# MVC. When you go to the page www.myPage/x/y the program will find the controller named xController (that is unless you do custom routing but don't mess with that for now) and find function y. If the function has a return type of ActionResult, then you will return a View(myModel) and the program will look for a view named y.cshtml and generate the HTML based on the view.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.