-1

Hi all I don't know is this possible or not ,that's why guys I need suggestion to achieve this .The thing is I want to post javacript object with ajax-beginform instead of model object to controller . i code like bellow but cant find a way to post the data ,I know jQuery ajax is an option ,but I don't want to use jQuery ajax for posting data in this case .

HTML

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts{
    <script type="text/javascript">

        var getValues=function()
        {
            //alert(1)
            var v = {
                id: $("#txtid").val(), name: $("#txtName").val()
            }
            console.log(v)
            return v;
        }

    </script>
    }

<h2>Index</h2>
@using (Ajax.BeginForm("postvalue", new AjaxOptions { HttpMethod="POST", OnBegin = "getValues" }))
{
    <input type="text" id="txtid" />
    <br />
    <input type="text" id="txtName" />
    <br />
    <button type="submit" value="Click" style="width:50px;height:50px">Click</button>
}

Contoller

namespace AjaxBeginForm.Controllers
{
    public class AjaxBeginFormController : Controller
    {
        // GET: AjaxBeginForm
        public ActionResult Index()
        {
            return View();
        }

        public void postvalue(searchValues objsearchValues)
        {

        }
    }

    public class searchValues
    {
        public Int64 id { get; set; }
        public string name { get; set; }
    }
}

I want to post data to controller and catch them in objsearchValues .

kuntal
  • 1,591
  • 2
  • 16
  • 36
  • You don't want to use `$.ajax()`? Why not? (what do you think `Ajax.BeginForm()` does - it use `$.ajax()` to post the data, so your already using it behind the scenes) –  Feb 17 '17 at 21:57
  • thats why I don't want to use this again .I just want to attach a object with values.Is it possible? – kuntal Feb 18 '17 at 06:09
  • What do you mean _I don't want to use this again_? Use what again? And why are you not just using `$.ajax()`? –  Feb 18 '17 at 06:12
  • I want to minize of use javascriptwhen we have inbuilt functionality in mvc. – kuntal Feb 18 '17 at 06:16
  • Seriously? Generate your controls correctly (with `name="id"` and `name="name"` and its `$.post('@Url.Action("postvalue")', $('form').serialize(), function(data) { ... })` - i.e. less code that you currently have. –  Feb 18 '17 at 06:19

1 Answers1

0

Put the JS value in a hidden field in the form and when the form is submitted it will pass the value back to the controller.

Kyle Johnson
  • 763
  • 1
  • 13
  • 31