0

I am using html helper for dropdownlist in javascript function but it's not working. I have tried using various syntax with or without encoder etc but it is rendering as string not as a html control. Actually I have to create dynamic dropdownlist each time my Add new row button is clicked. Placing the code for dropdownlist in view is working fine but in javascript file it is rendering as simple text.

addServer.js-Way1

function addServerRow() {
    var html = '<tr>' +
                '<td><input type="text" name="ServerAllNetworks.ServerPrivateNetworks[' + _totalRows + '].IPAddress" class="form-control" id="' + 'txtIpAddress' + _totalRows + '"></td>' +
                '<td>@Ajax.JavaScriptStringEncode(Html.DropDownListFor(m => m.ServerPrivateNetworks, ViewData["PrivateNetwork"] as List<SelectListItem>, "Select",new { Class = "form-control", data_required = "true"}).ToHtmlString())</td>' +
                '</tr>'
    $(html).appendTo($("#tblServerPrivateNw"))  
};
$("#btnAddPrivateServerNetwork").click(function (e) {
    e.preventDefault();
    _totalRows += 1;
    addServerRow();
});

I have tried the other way also to create dropdownlist it works fine but when I select item from the dynamically created dropdownlists I get null value in my controller on form submission. Below is the code used

addServer.js-Way2

function addServerRow() {
    var html = '<tr>' +
                '<td><input type="text" name="ServerAllNetworks.ServerPrivateNetworks[' + _totalRows + '].IPAddress" class="form-control" id="' + 'txtIpAddress' + _totalRows + '"></td>' +
                '<td><select class="form-control" name="ServerAllNetworks.ServerPrivateNetworks" id="' + 'drpPrivateNetwork' + _totalRows + '" /></td>' +
                '<td><input type="button" class="btnremove" value="-" /></td>' +
                '</tr>'
    $(html).appendTo($("#tblServerPrivateNw"))
            var drplist = document.getElementById('drpPrivateNetwork' + _totalRows);
            for (i = 0; i < allPrivateNetworks.length; i++) {
                var option = document.createElement('option');
                option.text = allPrivateNetworks[i].Name;
                option.value = allPrivateNetworks.Id;
                drplist.add(option, 0);
            }
};
$("#btnAddPrivateServerNetwork").click(function (e) {
    e.preventDefault();
    _totalRows += 1;
    addServerRow();
});

My model for this dropdownlist is ServerAllNetworks and dropdownlist is used to get PrivateNetworkId

public class ServerAllNetworks
{
    public ServerDetails server { get; set; }
    public List<ServerPrivateNetworkDetails> ServerPrivateNetworks { get; set; }
}

public class ServerPrivateNetworkDetails : ServerPrivateNetwork
{
    public string ServerName { get; set; }
    public string PrivateNetworkName { get; set; }
}
public partial class ServerPrivateNetwork
{
    public int ID { get; set; }
    public int ServerID { get; set; }
    public int PrivateNetworkID { get; set; }
    public string IPAddress { get; set; }
}

I can use any of the two ways please suggest which way is better and then suggest the solution for the problem faced in that way.

My controller code is

[HttpPost]
public ActionResult Add(FormCollection form, int ServerTypeID)
{
    GetDropDownList();
    ServerAllNetworks serverAllNetworks = new ServerAllNetworks();
    ServerDetails serverDetails = new ServerDetails();
    serverDetails.ServerName = Request["server.ServerName"].ToString();
    serverDetails.ServerTypeID = Convert.ToInt16((Request["server.ServerTypeID"]).ToString());
    serverDetails.Domain = Request["server.Domain"].ToString();
    serverDetails.NickName = Request["server.NickName"].ToString();
    serverDetails.ServiceProviderID = Convert.ToInt32(Request["server.ServiceProviderId"]);
    serverDetails.PublicIP = Request["server.PublicIP"];
    serverAllNetworks.server = serverDetails;
    var privateNetworkIdsList = Request["\"ServerPrivateNetworks\""];
    var newprivateNetworkIdsList = Regex.Replace(privateNetworkIdsList, "[^.0-9,]", "").Split(',').ToList();
    for (int i = 1; i <= newprivateNetworkIdsList.Count; i++ )
    {
        ServerPrivateNetworkDetails serverPrivateNetworkDetails = new ServerPrivateNetworkDetails();
        serverPrivateNetworkDetails.IPAddress = Request["ServerAllNetworks.ServerPrivateNetworks.IPAddress" + i].ToString();
        serverPrivateNetworkDetails.PrivateNetworkID = Convert.ToInt32(newprivateNetworkIdsList[0]);
        serverAllNetworks.ServerPrivateNetworks.Add(serverPrivateNetworkDetails);
    }
    //if (!ValidateServer(serverAllNetworks.server, ModelState))
    //{
    //    var result = AdminService.AddServer(serverAllNetworks);
    //    ViewBag.Message = result > 0 ? Message.ServerAddSuccessfully : Message.ServerAddError;
    //    SessionItems.ServerTypes = GetMenuItem();

    //    if (result > 0)
    //        return RedirectToAction("Dashboard", "Home");
    //}
    return View();
}

Currently I am using the way1 but have placed the code in view itself.Now the problem I am facing is for dropdown for servertypeid and serviceproviderid I am getting all values of dropdown not just the selected value. Please help.

ekad
  • 14,436
  • 26
  • 44
  • 46
rupinder18
  • 795
  • 1
  • 18
  • 43
  • 1
    where is your js code. In a external file 'myfile.js'? The JavaScript code has to be in the .cshtml file in order to the Html helpers to work – sabotero Feb 11 '15 at 10:55
  • ok...but if I want to use it in external js file...is there any way to achieve that? – rupinder18 Feb 11 '15 at 10:57
  • yo have to manualy create your `select` element and manualy add the `option`(s) elements or change your approach, using partials views – sabotero Feb 11 '15 at 12:19
  • 1
    I noticed you've already try that. For solve the null in the controller you can set to `ServerAllNetworks.ServerPrivateNetworks[i].PrivateNetworkIzd` the select element's name attribute. Where `i` is your `_totalRows` – sabotero Feb 11 '15 at 12:39
  • thanx for your replies...can you also tell me rather than using formcollection to get data in my controller how can I pass my model ServerAllNetworks directly to my controller..I tried using that but it gives null value but through formcollection values are accessible – rupinder18 Feb 11 '15 at 12:43
  • Post your controller code please – sabotero Feb 11 '15 at 12:44
  • what is your servertypeid? Can't you put it in your model too? – sabotero Feb 11 '15 at 12:56
  • its already there in ServerDetails class – rupinder18 Feb 11 '15 at 12:58
  • earlier before adding the dynamic row generation code I was using only serverdetails model than everything was working fine..used the same way for dropdownlist and in controller also earlier serverdetails model's data was accessible in controller but after changing the model I am able to access form data through formcollection and dropdown selected values are not accessible – rupinder18 Feb 11 '15 at 13:00

0 Answers0