0

I am facing an issue while sharing the same model between a view and its multiple partial views.

I have a main view MainView which has its own model MainViewModel. In this MainView, I have a few controls which are bound to properties in the MainViewModel.

On a button click I am opening a partial view from this MainView. Say SubView1. It is a partial view and it consists of several controls which are bound to the properties in MainViewModel. At some point user enters some values in this partial view SubView1 and clicks on a button to submit the data. During this time, I am posting the data to the controller like this :

$.ajax({
    type: "POST",
    url: "/MainViewController/SomeAction",
    data: JSON.stringify({ dataObj: dataArray }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    success: function (msg) {
        ServiceSucceeded(msg);
    },
    error: function () {
        return "error";
    }
});

SomeAction Code :

public void SomeAction(List<ModelClass> dataObj)
{
    if(dataObj != null)
    {

    }
}

My doubt is that, since the controls in this partial view are already bound to the MainViewModel properties, do I still need to pass it using json like this? Or can the data be directly accessed from the MainViewModel during a post method? I tried to pass the model to the post method, but its data remains as null.

My MainViewModel class :

private EnvironmentVariableTarget m_Markers;
private List<SelectListItem> startLocation = new List<SelectListItem>();
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string JobId { get; set; }
public string TaskId { get; set; }
public string TrajName { get; set; }
public int UserId { get; set; }
public DateTime StartPeriod { get; set; }
public DateTime EndPeriod { get; set; }
public int Aggr { get; set; }
public string MailId { get; set; }
public string StartLocation { get; set; }
public string EndLocation { get; set; }
public string lblGridHeaderTask { get; set; }
public string lblGridHeaderTraj { get; set; }
public string lblGridAggr { get; set; }
public string lblGridStartDate { get; set; }
public string lblGridEndDate { get; set; }
public int StartLocId { get; set; }
public int EndLocaId { get; set; }
public MySqlConnection databaseConnectionObj;
private MySqlCommand sqlCommandObj;
private Logger m_Logger;

These are the bound properties which I need :

public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string TrajName { get; set; }

When user clicks on add to list, I am adding to javascript array like this :

var obj = { TaskId: ccount, TrajName: $('#drpTraj').find(":selected").text(), StartTime: $('#txtStartTime').val(), EndTime: $('#txtEndTime').val(), Aggr: $('#drpAggrInterval').find(":selected").text() }
dataArray.push(obj)

I am keeping this array in js and when user clicks submit I am passing the entire array back to the controller. My question is at this point, I am getting the control's value. I am asking whether I can get the bound value at this time. ie the controls drpTraj, txtStartTime and drpAggrInterval are already bound to viewmodel properties.

My questions are :

  1. Is there any other way to tackle this scenario?
  2. If I want to pass one more data which is not bound to the viewmodel, then how to pass that?
  3. If databinding is not used, then is this the way to pass data ie using JSON?
ViVi
  • 4,339
  • 8
  • 29
  • 52
  • If the form controls have the correct `name` attributes that relate to your model, then they will be correctly bound. –  Nov 21 '16 at 05:05
  • Show us the code for SomeAction method – Mir Gulam Sarwar Nov 21 '16 at 05:53
  • @Mir : added the code. It is just a list of model class. – ViVi Nov 21 '16 at 06:41
  • @StephenMuecke : I was asking not about the binding. Binding works fine. I was asking about passing the bound data to controller. – ViVi Nov 21 '16 at 06:42
  • Passing how? If the name attributes are correct, it will be passed in the request if you make a normal POST. Not sure why you want to use ajax, but that can be done also just using the `data: $('form').serialize(),` ajax option. You have shown no code at all and not indicated what is `null` so impossible to help. –  Nov 21 '16 at 06:46
  • remove dataType: "json" because you are not returning json, also make a console.log(dataArray) before making ajax call to ensure data is already in the array. Let us know then – Mir Gulam Sarwar Nov 21 '16 at 06:53
  • @StephenMuecke: If I post the code, it will be too long. My requirement is bit different. Its not under a form. When the data in the form is submitted, it is not posted to the controller. Instead, the data is kept in javascript array `dataArray` as mentioned in my code. Finally the user submits all the entered data .. ie the `dataArray` can have multiple elements. ie why I am getting in the post method as `List dataObj`. It is a list of data. – ViVi Nov 21 '16 at 06:56
  • What is `dataArray`? All you need to show us is a simple example of what you trying to do - if `dataArray` contains as array of objects containing property names that match your model, then it will be correctly bound –  Nov 21 '16 at 06:59
  • Also don't forget to add [HttpPost] before your SomActionMethod – Mir Gulam Sarwar Nov 21 '16 at 07:06
  • @StephenMuecke : I have edited my question. Please check now. – ViVi Nov 21 '16 at 07:12
  • @Mir : Thanks for the advice. I will check and revert. – ViVi Nov 21 '16 at 07:13
  • First it should be `public ActionResult SomeAction(List dataObj)` (not `void`). Not entirely sure what the issue is? Do you want to add the current values of the form controls to the array before posting? (although its very unclear why you doing this instead of dynamically adding form controls for the collection) –  Nov 21 '16 at 07:20
  • It is a requirement. We are required to generate an html list first when user submits each item, storing the data in the array at the same time. Finally when user is about to submit, the entire array need to be passed. I want to know if it is possible to get the bound data from the model. – ViVi Nov 21 '16 at 07:25
  • Of course. But why are you doing it this way. You have no validation at all. The user cant see what they have previously entered. If anything is invalid when you submit, you cannot display the previous data. If you wanting to dynamically add collection items, refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for some options –  Nov 21 '16 at 07:33

2 Answers2

0

Check Below Code for passing model data through JSON :

//Your Master Model Properties 
    public partial class YourMasterModel
        {
             public List<YourModel> YourMasterModelList{ get; set;  }
             public YourModel YourModel{ get; set; }
         }    

   //Your Model Properties 
    public partial class YourModel
        {
            public int Id { get; set; }
            public string Param1 { get; set; }
            public string Param2 { get; set; }
            public int[] SelectedListOptions { get; set; }
        }
    //Your Ajax Call along with Your Model
    $("#Addbtn").click(function () {
    var YourModel = {
                    "Id": $("#hdnId").val(),
                    "Param1": $("#Param1").val(),
                    "Param2": $("#Param2").val()

                };

 var YourMasterModel = {

                    "YourMasterModelList": //You have to create a list of YourModel through for loop and stored into a list variable and pass this to here
                    "YourModel": YourModel
                };
                $.ajax(
                 {
                     url: '/MainViewController/SomeAction/',
                     type: "Post",
                     async: false,
                     dataType: "html",
                     data: JSON.stringify(YourMasterModel),
                     contentType: "application/json;charset=utf-8",
                     success: function (result) {
                         $("#YourResultDiv").html("");
                     }
                 });
       });
    //Your Action with your model 

            /// <summary>
            /// Add Data
            /// </summary>
            /// <param name="YourModel"></param>
            /// <returns></returns>
            [HttpPost]
            public ActionResult AddDataWithModel(YourMasterModel objYourMasterModel)
            {
            //Here you will get the list of yourmodel data
            var listofdata=objYourMasterModel.YourMasterModelList;
            return PartialView("_YourPartialView");
            }

Hope this will help you !!

Laxman Gite
  • 2,248
  • 2
  • 15
  • 23
-3

If you want to pass parameter into post method use below technique:

@using (Ajax.BeginForm("action", "controller", null, new AjaxOptions() { OnSuccess = "" }, new { @class = "form-horizontal", role = "form", id = "id" }))
{ 
    //put partial view code into the these brackets 
}

If you want to do ajax, then you need to pass data into data:

// all columnname same name as data model of action 
data: {  
    "columnname1": "John",  
    "columnname2": "Smith",    
    "columnname2": "man",    
    "columnname3": 32
}  
kayess
  • 3,384
  • 9
  • 28
  • 45
Raju Mali
  • 185
  • 4