单击“创建”按钮时尝试触发javascript事件

时间:2017-06-27 21:29:40

标签: javascript jquery asp.net-mvc

我正在尝试获取一个javascript事件来执行和更新我的mvc代码中的数据库。

到目前为止,对于javascript:

<script type="text/javascript">

    function init()
    {
        document.getElementById("Create").onclick = codeAddress;
        alert('click');
    }


    function codeAddress()
    {

        alert('codeAddress');
        var street = document.getElementById('VenueAdd');
        var city = document.getElementById('VenueCity');
        var state = document.getElementById('VenueState');
        var zip = document.getElementById('VenueZip');
        var address = street + city + state + zip

        alert(address);

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.mapsGeocoderStatus.OK) {

                alert(status + ' is the status');

            }
            else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }



    });

我希望在点击此按钮时执行

        <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" onclick="init();"/>
        </div>
    </div>

这也会触发&#34;创建&#34;控制器中的事件是这段代码:

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "VenueID,VenueName,VenueAdd,VenueCity,VenueState,VenueZip,VenuePhone,VenueFax,VenueContactName,VenueContactEmail,VenueContactPhone,VenueWebsite,VenueLat,VenueLong,VenueRating")] Venue venue)
    {
        try
        {
            if (ModelState.IsValid)
            {


                db.Venues.Add(venue);
                db.SaveChanges();






                return RedirectToAction("Index");
            }
        }
        catch (DataException /*dex*/)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes.  Try again, and if the problem persists see your administrator");
        }

        return View(venue);
    }

我希望它执行javascript然后将记录插入数据库。

我不确定我是否会以正确的方式解决这个问题,我对任何建议持开放态度。

1 个答案:

答案 0 :(得分:0)

除了完成这项工作之外,你应该努力使你的JS尽可能不引人注目(从你的html dom中获取你的js)

Html:

<div class="btn btn-default submitMe"/>

JS

$(document).ready(function () {
     $('.submitMe').click(function () {
       codeAddress();
     });
});

function codeAddress()
{
   ALL YOUR CODE ADDRESS STUFF HERE
   $('#ID-OF-YOUR-FORM-HERE').submit();
});