0

I'm moving from WPF development to Asp MVC and have started doing an Asp MVC app. So far I've set up my:

  • model

  • controller

and

  • view(with the relevant fields.)

The next step involves sending the data entered in my form to the controller on the Submit button click.

I know in WPF I can bind the control properties to a property in the viewmodel, also there would be a click event on the button which I don't see in MVC.

This is my pseudo understanding of how to do that in MVC but correct me if I' wrong (Model is of type Case):

1.Set button click event to send form data to controller.

2.Pass data into controller constructor and assign to typed Case object.

Question:

How can you pass view values on button submit to a typed object in a controller?

Code:

View -

      <form action="" method="post">
            <div class="form-horizontal">
                <div class="col-lg-6">


                        <!-- SELECT STATUS STATIC-->
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="Current Status">Status</label>
                            <div class="col-md-8">
                                <select id="Status" name="Status" onchange="" class=" form-control">
                                    <option value="Down">Down</option>
                                    <option value="Up">Up</option>
                                </select>
                            </div>
                        </div>


                        <!-- SELECT APP STATIC-->
                        <div class="form-group">
                            <label class="col-md-3 control-label"  for="App">App</label>
                            <div class="col-md-8" >
                                <select id="App" name="App" onchange="" class=" form-control">
                                    <option value="SAP">SAP</option>
                                    <option value="JAP">JAP</option>
                                </select>
                            </div>
                        </div>

                       <asp:Button id="b1" Text="Submit" runat="server" />

                </div>
            </div>
        </form>            <!--

Controller -

public class CaseController : Controller
{


    public ActionResult Index()
    {
        return View();
    }

}

Model -

Public class Case
{
   public string Status { get; set; }
   public string App { get; set; }

}
Brian Var
  • 6,029
  • 25
  • 114
  • 212
  • You just need a an `` which will submit the name/value pairs or your form controls to a POST method. Suggest you go to the MVC site and work through the tutorials to learn the basics –  May 10 '16 at 23:05

3 Answers3

1

In the view just add a button in the form like

<button id="b1" Text="Submit"/>

In the controller add an action method to handle the post.

public class CaseController : Controller
{
  [HttpPost]
  public ActionResult Index(Case case)
    { 
      //Do Something
      return View();
    }

    public ActionResult Index()
    {

     return View();
    }
}

You may also want to look into using Razor and strongly typed views. Makes things much simpler.

etoisarobot
  • 7,684
  • 15
  • 54
  • 83
1

another approach is to use mvc ajax call, by doing these you also can pass parameter to controller from simple parameter to a selected row in gridview.

  1. On the view in the button control add onclick property that point to a javascript function and passing parameter. In these sample will get selected row on the gridview

    <input id="GenerateData" type="button" value="GenerateData" onclick="generateData(App.grdNameOfGridview.getRowsValues({selectedOnly:true}) [0]);" />

  2. On the view create a javascript function that use ajax to call the controller, note the paramater that can be passing from click button event to the javascript function that will use ajax to call the controller. In this sample i use extjs framework, if you want you can also use jquery as well

    generateData= function (recordData) { var jsonStringContractUnit = JSON.stringify(recordData); Ext.Ajax.request({ url: '../ControllerName/GenerateData', method: 'POST', params: { SelectedContractUnit: jsonStringContractUnit },

  3. On the controller the parameter will be pass from view and will be store on SelectedData

    public ActionResult GenerateData(string SelectedData) { }

1

I hope that I understand your scenario well? You have a form with two drop down lists and a submit button? When you click the submit button you want to extract the selected values? This is how I understand it and this is how I will try to explain my answer with examples.

I would suggest that you bind your view/page to a view model. A view model is a kind of model that will represent your data in the view, whether it be textboxes, drop down lists, textareas, radio buttons, checkboxes, etc. It can also display static text on your view. I wrote a detailed answer as to what a view model is, if you have the time please go and read it:

What is ViewModel in MVC?

Go and create your view model. It will contain two lists that will represent your two drop down lists. Each list has an id associated with it that will contain the value of the selected drop down list item:

public class CaseViewModel
{
     public int StatusId { get; set; }

     public List<Status> Statuses { get; set; }

     public int AppId { get; set; }

     public List<App> Apps { get; set; }
}

Your domain models, namely Status and App, for the above mentioned lists:

public class Status
{
     public int Id { get; set; }

     public string Name { get; set; }
}

public class App
{
     public int Id { get; set; }

     public string Name { get; set; }
}

Now that you have this setup your next step is to populate these lists in your controller's action method. Ideally you would populate it with values from a database, but in your case I guess it is ok to hard code these values:

public ActionResult Index()
{
     CaseViewModel model = new CaseViewModel();

     model.Statuses = new List<Status>();
     model.Statuses.Add(new Status { Id = 1, Name = "Down" });
     model.Statuses.Add(new Status { Id = 2, Name = "Up" });

     model.Apps = new List<App>();
     model.Apps.Add(new App { Id = 1, Name = "SAP" });
     model.Apps.Add(new App { Id = 2, Name = "JAP" });

     return View(model);
}

As soon as you have populated your two lists, you pass the view model directly to the view. The view will receive a strongly type model and will do with it what it needs to do with it. In your case, a form will be created with two drop down lists and a submit button. I have left out all your CSS for clarity (just go and add it):

@model WebApplication_Test.Models.CaseViewModel

@using (Html.BeginForm())
{
     <div>
          @Html.DropDownListFor(
               m => m.StatusId,
               new SelectList(Model.Statuses, "Id", "Name", Model.StatusId),
               "-- Select --"
          )
          @Html.ValidationMessageFor(m => m.StatusId)
     </div>
     <div>
          @Html.DropDownListFor(
               m => m.AppId,
               new SelectList(Model.Apps, "Id", "Name", Model.AppId),
               "-- Select --"
          )
          @Html.ValidationMessageFor(m => m.AppId)
     </div>
     <div>
          <button type="submit">Submit</button>
     </div>
}

So now you have two drop down lists populated with data. Select a value in each and press the submit button. Your view is bound to a view model and will retain values on form submission. Values in lists are not kept on form submission and will need to be populated again:

[HttpPost]
public ActionResult Index(CaseViewModel model)
{
     // Check form validation
     if (!ModelState.IsValid)
     {
          // If validation fails, rebind the lists and send the current view model back
          model.Statuses = new List<Status>();
          model.Statuses.Add(new Status { Id = 1, Name = "Down" });
          model.Statuses.Add(new Status { Id = 2, Name = "Up" });

          model.Apps = new List<App>();
          model.Apps.Add(new App { Id = 1, Name = "SAP" });
          model.Apps.Add(new App { Id = 2, Name = "JAP" });

          return View(model);
     }

     // Form validation succeeds, do whatever you need to do here
     return RedirectToAction("Index");
}

I hope this helps.

Community
  • 1
  • 1
Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234