2017-02-27 2 views
0

Ich versuche, einen Wert aus einer Ansicht in aps.net mvc zu lesen: Ich bin mir bewusst, dass dies wie ein sehr grundlegendes Problem scheint, jedoch konnte ich keine Lösung dafür finden, also bin ich Wenden Sie sich an Sie: In meinem Fall scheint es, als ob der Parameter playlistModel.Model.Name nie gesendet wird, oder zumindest null ist.Fehlerbehebung einfache create-from

Mein Controller:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(PlaylistViewModelDetails playlistModel) 
{ 
    if (!String.IsNullOrEmpty(playlistModel.Model.Name)) 
    { 
     //this is never called due to playlistModel.Model.Name being null. 
     return RedirectToAction("Index"); 
    } 
    return View(playlistModel); 
} 


@model Orpheus.Models.ViewModels.PlaylistViewModelDetails 
@using (Html.BeginForm()) 
{ 
@Html.AntiForgeryToken() 

<div class="form-horizontal"> 
    <hr /> 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Model.Name, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Model.Name, "", new { @class = "text-danger" }) 
     </div> 
    </div> 

    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Erstellen" class="btn btn-default" /> 
     </div> 
    </div> 
</div> 
} 


public class PlaylistViewModelDetails 
{ 
    public PlaylistModel Model = new PlaylistModel(); //a seperate class containing a string value, which must be read from the form 
} 

Vielen Dank für die Hilfe, dieses Problem zu lösen!

Antwort

1

Ihr PlaylistViewModelDetails enthält nur ein Feld für Model. Die DefaultModelBinder bindet nur Eigenschaften, keine Felder.

Ihr Modell ändern zu

public class PlaylistViewModelDetails 
{ 
    public PlaylistModel Model { get; set; } 
} 

und einen Parameter losen Konstruktor hinzufügen, wenn Sie PlaylistModel

public PlaylistViewModelDetails() 
{ 
    Model = new PlaylistModel(); 
} 

Beachten Sie auch Name in PlaylistModel auch eine Eigenschaft sein müssen initialisiert werden soll.

+0

Vielen Dank, das hat es für mich gelöst :) –