We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: November 16, 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Initial selected item for DropDownlListFor

Thread ID:

Created:

Updated:

Platform:

Replies:

128187 Jan 6,2017 03:16 PM UTC Jan 12,2017 11:52 AM UTC ASP.NET MVC 6
loading
Tags: AutoComplete
Bernard Jurlina
Asked On January 6, 2017 03:16 PM UTC

How can I initially select item in DropDownListFor control based on model filed value? For example, I have this in my view:
@Html.EJ().DropDownListFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).DropDownListFields(df => df.Text("Naziv").Value("MjestoID")).SelectedIndex(1)

How can I replace index 1 for SelectedIndex based on m => m.MjestoID so that I get selected value when my edit view opens?

The same question I have for AutocompleteFor control.
@Html.EJ().AutocompleteFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).PopupHeight("200px").PopupWidth("200px").ShowRoundedCorner(true)

Thanks!

Bernard Jurlina
Replied On January 7, 2017 12:39 PM UTC

Update

DropDownFor control works like this:
@Html.EJ().DropDownListFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).DropDownListFields(df => df.ID("MjestoID").Text("Naziv").Value("MjestoID")).Text(Model.Mjesto.Naziv)

For Autocomplete control, I manage to select value from Model on edit view open like this:
Html.EJ().AutocompleteFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).Value(Model.Mjesto.Naziv)

 but when I click Save, I get this error:

Object reference not set to an instance of an object.

Line 87:                 @*@Html.DropDownList("MjestoID", null, htmlAttributes: new { @class = "form-control" })*@
Line 88: 
Line 89:                 @Html.EJ().AutocompleteFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).Value(Model.Mjesto.Naziv)
Line 90:                 @*@Html.EJ().AutocompleteFor(m => m.MjestoID, (Syncfusion.JavaScript.Models.AutocompleteProperties)ViewData["mjesto"])*@
Line 91: 

Thanks!

Prince Oliver [Syncfusion]
Replied On January 10, 2017 08:40 AM UTC

Hi Bernard,  
  
Thanks for contacting Syncfusion support,  
  
We were unable to reproduce the reported issue with Autocomplete using the shared code. We have prepared a sample with AutocompleteFor using Model binding and set value for it using Model data. On post action issue was not reproduced in our end.  

Please find sample in link below:  
  
If this doesn’t resolve the issue at your end, could you please share us modified sample to reproduce the issue at our end. Also share us the model data used and the way you want to maintain Autocomplete selection on post in your application This would be very helpful for us to analyze and provide more appropriate solution.  
  
Regards,  
Prince 


Bernard Jurlina
Replied On January 10, 2017 09:39 PM UTC

Hi Prince!

In Your example, there is no updating model data from Edit view, and that's where I'm getting error described in my first post.
My entity from the Model is like this:

public partial class Firma
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Firma()
{
this.FirmaRacun = new HashSet<FirmaRacun>();
this.UsersFirma = new HashSet<UsersFirma>();
this.Zaposleni = new HashSet<Zaposleni>();
this.Jedinica = new HashSet<Jedinica>();
this.PNListaOstTroskova = new HashSet<PNListaOstTroskova>();
this.PNListaPrijSredstava = new HashSet<PNListaPrijSredstava>();
this.PNListaRelacija = new HashSet<PNListaRelacija>();
this.PNListaZadaca = new HashSet<PNListaZadaca>();
this.PNNalozi = new HashSet<PNNalozi>();
}

public int FirmaID { get; set; }
public string Naziv { get; set; }
public string OIB { get; set; }
public Nullable<int> UlicaID { get; set; }
public Nullable<short> Kbr { get; set; }
public string DodKbr { get; set; }
public Nullable<int> MjestoID { get; set; }
public string Telefon { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public string MB { get; set; }
public string MBS { get; set; }
public Nullable<int> VrstaID { get; set; }
public string SifraDjelatnosti { get; set; }
public string NazivDjelatnosti { get; set; }
public bool SustavPDV { get; set; }
public string PDVBroj { get; set; }
public Nullable<System.DateTime> DatumKreiranja { get; set; }
public bool Aktivna { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FirmaRacun> FirmaRacun { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<UsersFirma> UsersFirma { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Zaposleni> Zaposleni { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Jedinica> Jedinica { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PNListaOstTroskova> PNListaOstTroskova { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PNListaPrijSredstava> PNListaPrijSredstava { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PNListaRelacija> PNListaRelacija { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PNListaZadaca> PNListaZadaca { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PNNalozi> PNNalozi { get; set; }
public virtual FirmaVrsta FirmaVrsta { get; set; }
public virtual Mjesto Mjesto { get; set; }
public virtual Ulica Ulica { get; set; }
}

My controller for edit view is like this:

public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Firma firma = db.Firma.Find(id);
if (firma == null)
{
return HttpNotFound();
}
ViewBag.VrstaID = new SelectList(db.FirmaVrsta, "VrstaID", "Naziv", firma.VrstaID);
ViewBag.UlicaID = new SelectList(db.Ulica, "UlicaID", "Naziv", firma.UlicaID);

ViewBag.Mjesto = db.Mjesto.OrderBy(m => m.Naziv).ToList();
return View(firma);
}

and my group in view is like this:

<div class="form-group">
@Html.LabelFor(model => model.MjestoID, "Mjesto", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EJ().AutocompleteFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).Value(Model.Mjesto.Naziv)
@Html.ValidationMessageFor(model => model.MjestoID, "", new { @class = "text-danger" })
</div>
</div>

The thing is that when I open the edit view, AutocompleteFor shows selected value like it should, the one from the model (.Value(Model.Mjesto.Naziv)), but when change it, and click on Save:

Object reference not set to an instance of an object.

Line 87:                 @*@Html.DropDownList("MjestoID", null, htmlAttributes: new { @class = "form-control" })*@
Line 88: 
Line 89:                 @Html.EJ().AutocompleteFor(m => m.MjestoID).Datasource((IEnumerable<Mjesto>)ViewBag.Mjesto).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).Value(Model.Mjesto.Naziv)
Line 90:                 @*@Html.EJ().AutocompleteFor(m => m.MjestoID, (Syncfusion.JavaScript.Models.AutocompleteProperties)ViewData["mjesto"])*@
Line 91: 



Arun Palaniyandi [Syncfusion]
Replied On January 11, 2017 11:45 AM UTC

 
 Hi Bernard,   
   
Thanks for the update, 
 
We have modified our same sample by updating model data from Edit view as you have asked and still we are unable to reproduce the issue. You have mentioned that error occurs, when you click on the save button. Hence, we suspect that the issue might be in the save action. So could you share the details on your save action so that it would be helpful for us to find the root cause for issue? Also you can modify the shared sample or share a simplified sample based on your scenario to reproduce the issue at our end and provide an appropriate solution.  
 
Please find the modified sample below: 
 
Please let us know if you have any queries,  

Regards, 
Arun P 


Bernard Jurlina
Replied On January 11, 2017 08:23 PM UTC

Hi Arun,

here is the code in my Edit post:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FirmaID,Naziv,OIB,UlicaID,Kbr,DodKbr,MjestoID,Telefon,Fax,Email,MB,MBS,VrstaID,SifraDjelatnosti,NazivDjelatnosti,SustavPDV,PDVBroj,DatumKreiranja,Aktivna")] Firma firma)
{
if (ModelState.IsValid)
{
db.Entry(firma).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.VrstaID = new SelectList(db.FirmaVrsta, "VrstaID", "Naziv", firma.VrstaID);
ViewBag.UlicaID = new SelectList(db.Ulica, "UlicaID", "Naziv", firma.UlicaID);
return View(firma);
}

When I press save button, ModelState is not valid and the error is
"The value 'OSIJEK' is not valid for MjestoID."

Somehow, the autocomplete control are not sending ID value from selected option. It sends string "OSIJEK" instead of number 2, which is ID for OSIJEK.

Hm, I cannot see what I'm doing wrong.

Thanks!



Arun Palaniyandi [Syncfusion]
Replied On January 12, 2017 11:52 AM UTC

Hi Bernard,      
      
Thanks for your update,    
  
Based on the analysis of your shared code, we found that you had sent the key value to the controller. Hence, in your Autocomplete you could not directly send the key value to the code behind. If you want to get the key in controller directly using the Autocomplete ID then, you have to define a hidden input element and set its value on Select event. Refer to the below code sample.    
   
[CSHTML]   
<div class="form-group">   
            @Html.LabelFor(model => model.Naziv, htmlAttributes: new { @class = "control-label col-md-2" })   
            <div class="col-md-10">   
                <input type="hidden" id="Naziv_hidden" name="Naziv" />    
                @Html.EJ().AutocompleteFor(model => model.Naziv).Datasource((IEnumerable<DPForModel126.Models.Mjesto>)ViewBag.data).AutocompleteFields(df => df.Text("Naziv").Key("MjestoID")).PopupHeight("200px").PopupWidth("200px").ShowRoundedCorner(true).Value(Model.Naziv).ClientSideEvents(c => c.Select("onSelect"))    
                @Html.ValidationMessageFor(model => model.Naziv)   
            </div>   
        </div>   
[Script]    
    function onSelect(args) {    
        $("#Naziv_hidden").val(args.key);   
    }    
[Controller]    
  
[HttpPost]   
        public ActionResult Edit(string Naziv)   
        {   
            int Id = Int32.Parse(Naziv);   
            var std = List.Where(s => s.MjestoID == Id).FirstOrDefault();   
            ViewBag.data = List;   
            return View(std);   
        }   
  
  
   
Please let us know if you have any more queries.     
  
Regards,    
Arun P.    


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

;