开发者

Instant Item Insertion in to LinqToSql Database with jquery in MVC 3

Here is my question i ve a Create View i wanna add a new item into my linqtosql database and fill my selectlist with updated database items in it and i want it to happen instantly when i click "+" button near my input its value will be saved and added into my selectlist. How can i achive this. I was thinking on json usage but couldnt figure it out.

MY Controller

    public JsonResult Productlist(string ipro, Product prod, int productId)
    {
        prod.name = ipro;
        db.Products.InsertOnSubmit(prod);
        db.SubmitChanges();
        int pro = Convert.ToInt32(db.Products.Where(x => x.name == ipro).Select(x => x.id).Single());
        IEnumerable<SelectListItem> ProductItems = db.Products.Where(d => d.id == pro).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList data = new SelectList(ProductItems, "Value", "Text");
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    //
    //Fill Design List..
    public JsonResult GetDesigns(int productId)
    {
        IEnumerable<SelectListItem> DesignItems = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList des = new SelectList(DesignItems, "Value",开发者_StackOverflow "Text");
        return Json(des, JsonRequestBehavior.AllowGet);
    }

My View (jquery)

(jquery)

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.js")"></script>
<script type="text/javascript" charset="utf-8">
    $("#ProductSub").click(function () {
        if ($("#iProduct").val() == "") {
            $("#iProduct").css({ backgroundColor: '#FFBBBB' });
        } else {
            $("#iProduct").css({ backgroundColor: '' });
            var inpro = $("#iProduct").val();
            $getJSON('@Url.Content("~/Admin/ProductSubmit/")', { ipro: inpro }, function (data) {
                $("select#Product").empty();
                $('select#Product').append('<option value="0">Please Select Design</option>');
                $.each(data, function (i, c) {
                    $('select#Product').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                })
                $("select#Product option:first").attr('selected', 'selected');
                $("select#Product").change(productlist);
            })
        }
    });

    function productlist() {
        var prod = $("select#Product option:selected").val();
        if (prod == "" || prod == 0) {
            $("select#Design").attr('disabled', 'true');

        } else {
            $.getJSON('@Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {
                $("select#Design").empty();
                $("select#Design").append('<option value="0">Please Select Design</option>');
                $.each(data, function (i, c) {
                    $('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                })
                $("select#Design").removeAttr('disabled');
                $("select#Design option:first").attr('selected', 'selected');
            })
        }
    }
</script>

View

<fieldset>
        <legend>Create New(All Fields Required)</legend>

        <div class="editor-label">Product</div>
        <div class="editor-field">
            <input id="iProduct" type="text"/>  
            @Html.ValidationMessageFor(model => model.Products.name )
        </div>
            @Html.DropDownList("Product", new SelectList((System.Collections.IEnumerable)ViewData["Productlist"], "id", "name"),"Please Select Product", new { onchange = "productlist()", style = "width:190px; padding:4px; margin:4px;" })
            <input id="ProductSub" type="button" style="padding:5px; margin-top:15px;" value="+" />

        <div class="editor-label">Design</div>
        <div class="editor-field">
            <input id="iDesign" type="text"/>  
            @Html.ValidationMessageFor(model => model.Design.name)
        </div>
            <select id="Design" style="width:190px; padding:4px; margin:4px;" onchange="designlist()"  >
            <option label="Please Select Design" selected="selected"></option>
            </select>
</fieldset>

Cause of im new around it doesnt allow me to put a picture about situation so i putted a link instead shows my page..

http://i51.tinypic.com/33ejvvb.jpg


Controller

public class AdminController : Controller
{
    public linqVipDataContext db = new linqVipDataContext();


    public JsonResult ProductSubmit(string ipro, Product prod)
    {
        prod.name = ipro;
        db.Products.InsertOnSubmit(prod);
        db.SubmitChanges();
        int pro = Convert.ToInt32(db.Products.Where(x => x.name == ipro).Select(x => x.id).Single());

        /*After saving changes to the db we create a new list to see the change instantly on page.*/

        IEnumerable<SelectListItem> Items = db.Products.Where(d => d.id == pro).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList data = new SelectList(Items, "Value", "Text");
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDesigns(int productId)
    {
        /*Here we create a list that will be posted as Json data*/

        IEnumerable<SelectListItem> Items = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList data = new SelectList(Items , "Value", "Text");
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}

View(Jquery)

/*-----New Entry Buttons-----*/

function productsub() {

    var prod = $("#iProduct").val();

    if (prod == "" || prod == " ") {

        $("input:text#iProduct").css({ 'background-color': '#FFBBBB' });

    } else {

        $('input:text#iProduct').css({ 'background-color': 'white' });
        var inpro = $("input:text#iProduct").val();

        $getJSON('@Url.Content("~/Admin/ProductSubmit/")', { ipro: inpro }, function (data) {

            $("select#Product").empty();
            $('select#Product').append('<option value="0">Please Select Product</option>');

            $.each(data, function (i, c) {

                $('select#Product').append('<option value="' + c.Value + '">' + c.Text + '</option>');

            })

            $("select#Product option:first").attr('selected', 'selected');
            $("select#Product").change(productlist);
        })
    }
}

/*-----DropdownLists-----*/

function productlist() {

    var prod = $("select#Product option:selected").val();

    if (prod == "" || prod == 0) {

        $("select#Design").attr('disabled', 'true');

    } else {

        $.getJSON('@Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {

            $("select#Design").empty();
            $("select#Design").append('<option value="0">Please Select Design</option>');

            $.each(data, function (i, c) {

                $('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');

            })

            $("select#Design").removeAttr('disabled');
            $("select#Design option:first").attr('selected', 'selected');
            $("select#Design").change(designlist);

        })
    }
}

View (HTML)

<fieldset>
        <legend>Create New(All Fields Required)</legend>

        <div class="editor-label">Product</div>
        <div class="editor-field">
            <input id="iProduct" type="text"/>  
            @Html.ValidationMessageFor(model => model.Products.name )
        </div>
            @Html.DropDownList("Product", new SelectList((System.Collections.IEnumerable)ViewData["Productlist"], "id", "name"),"Please Select Product", new { onchange = "productlist()", style = "width:190px; padding:4px; margin:4px;" })
            <input id="ProductSub" type="button" style="padding:5px; margin-top:15px;" value="+" />

        <div class="editor-label">Design</div>
        <div class="editor-field">
            <input id="iDesign" type="text"/>  
            @Html.ValidationMessageFor(model => model.Design.name)
        </div>
            <select id="Design" style="width:190px; padding:4px; margin:4px;" onchange="designlist()"  >
            <option label="Please Select Design" selected="selected"></option>
            </select>
</fieldset>

So this is how it happens actually I was perfectly going on with the code till I see my real problem is calling the buttons function in jQuery.

So if you have a problem with $(#Itemid).click(function() { } ); than try using function ItemFunc() { } and call function with onchange="ItemFunc()" on your html list..

Hope it's useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜