使用JSON将ViewModel传递给Controller

时间:2014-11-14 11:23:47

标签: jquery asp.net-mvc json entity-framework

我在将ViewModel数据传递给Controller时遇到问题。你能帮我么?

以下是有问题的代码的一部分......所有可能性都无法正常工作,在Controller中,值仍然为空...... :-(

我的ViewModel:

public class NabidkaCreateViewModel
{
    public List<Items> ItemsList = new List<Items>();

    public Guid? ItemsGlobalId { get; set; }
    public virtual ICollection<ItemsGlobal> ItemsGlobal { get; set; }
}

我的观点:

@using (Ajax.BeginForm("CreateOffer", "Offers", new AjaxOptions { UpdateTargetId = "result", HttpMethod = "POST", OnComplete = "Redirectfunction" }))
{  
    @Html.DropDownList("ItemsGlobalId", null, htmlAttributes: new { id = "PolozkaSelector", @class = "form-control" })

    <input id="PridatPolozku" type="button" value="Přidat" class="btn btn-lg btn-primary" />

    <div id="result" class="col-md-12 h5">
        @Html.Partial("_PolozkyNabidky", Model)
    </div>
}

脚本:

$(document).ready(function (event) {
    $("#PridatPolozku").click(function () {
        var Id = $("#PolozkaSelector").val();
        var parsedData = ( ItemsGlobalId: Id,  N: @Html.Raw(Json.Encode(Model.ItemsList)));

        $.ajax({
            type: "GET",
            url: "@Url.Action("AddPolozka", "Offers")",
            data: parsedData,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            cache: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            $("#result").html(result);
            alert("Return OK... ";

        }
    });
    });
});

我的控制器:

[HttpGet]
public async Task<ActionResult> AddPolozka(string ItemsGlobalId, NabidkaCreateViewModel N)
    {
        Guid IDtemp = new Guid(ItemsGlobalId); 

        ItemsGlobal IG = new ItemsGlobal();
        Items I = new Items();  
        IG = await db.ItemsGlobals.FindAsync(IDtemp);

        I.NadpisCZ = IG.NadpisCZ;
        I.NadpisEN = IG.NadpisEN;
        I.NadpisDE = IG.NadpisDE;
        I.TextCZ = IG.TextCZ;
        I.TextEN = IG.TextEN;
        I.TextDE = IG.TextDE;  
        I.Cena = IG.Cena;
        I.DobaVyroby = IG.DobaVyroby;
        I.SlevaHodnota = 0;
        I.JednotkyId = IG.JednotkyId;           
        I.KurzMenaId = IG.KurzMenaId;          

        N.ItemsList.Add(I);

        return PartialView("_PolozkyNabidky", N);             
    }     

0 个答案:

没有答案