-1

I have following view and controller code:

Index.cshtml

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <span style="color:green; font-weight:bold;" id="Message">@ViewBag.Message</span>
    <input type="text" id="txtMessage" />
    <input type="submit" id="btnSubmit" value="Submit" />
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">

    $('#btnSubmit').click(function (event) {
       
        $.ajax({
            type: "POST",
            url: "/Home/Create",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            data: JSON.stringify({
                'message': $('#txtMessage').val()
            })
        });

    });
</script>

Controller code:

public class HomeController : Controller
{
    public ActionResult Index(string message)
    {
        return View();
    }
    
    [HttpPost]
    public ActionResult Create(string message)
    {
        ViewBag.Message = message;

        return View("Index");
    }
}

After clicking the button and making ajax call I'm not able to see the message set in the Create method to ViewBag.Message inside the index view.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mohan Raju
  • 59
  • 8

1 Answers1

0

If you are using Begin form and button type as submit then why write ajax method?

Remove your btnSubmit click from javascript code and use textbox as TextBoxFor,

@Html.TextBoxFor(m => m.message, new { @class = "form-control" })

it should work.

Update Answer for without strongly type

As per code, you are using Begin Form so not required to ajax call. So first remove javascript code or if you keep that code so no meaning of that.

Now need to update the following line:

    <input type="text" id="txtMessage" **name = "txtMessage"** />

And in the controller code post method the following name should be the same.

[HttpPost]
public ActionResult Create(**string txtMessage**)
{
    ViewBag.Message = **txtMessage**;

    return View("Index");
}
Malvik Bhavsar
  • 407
  • 5
  • 8