Hi all Currently I have a website that has a button and some javascript that creates a loading look and then runs this actionresult. I want to add parameters to actionresult but not sure how to do it. Thanks! Here is my code
Controller:
[HttpPost]
public ActionResult PostMethod(string MyText)
{
System.Threading.Thread.Sleep(5000);
return Json("And were done");
}
View:
<input type="text" name="MyTextBlock"/>
<p id="PID">
Default message from declarative syntax.
</p>
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
opacity: .8; filter: alpha(opacity=70);display:none" >
<p style="position: absolute; top: 30%; left: 45%; color: White;" align="center">
<img src="../../Content/themes/base/images/ajax-loading.gif"><br />
Loading, please wait...
</p>
</div>
<button onclick="JavascriptFunction();">HTTPPost Button</button>
<script type="text/javascript" language="javascript">
function JavascriptFunction() {
var url = '@Url.Action("PostMethod", "MyTextBlock", new { MyText = "john" })';
$("#divLoading").show();
$.post(url, null,
function (data) {
$("#PID")[0].innerHTML = data;
$("#divLoading").hide();
});
}
</script>
What I want to do is pass MyTextBox into PostMethod to use it as MyText. Some of the other examples I have seen hardcode in values where I want it to be from the textbox. Any help is greatly appreciated. Thanks!
It seems like you’re trying to hand code a lot of what MVC already handles for you. Try this out…
First out, create a model for your view. You can call this whatever you want. Put the properties that you want as your parameters to your action method in here.
YourModel.cs
For your controller, you’ll have to change two things. The GET action for the page will need a model passed to it, like shown below.
For the POST action, change your
string MyTextparameter toYourModel model. This will allow MVC to bind your inputs on your view to the model.Action Method
PostMethod.cshtml
Some benefits of doing it this way is now your JS doesn’t have to change if you add more properties to your model. You just add another input to your view using either the HtmlHelper or hand code the input name with the name attribute equal to the name of the property on your model. MVC will handle the rest.