Click here to Skip to main content
16,019,018 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hello

how can i send a variable in javascript to one model in mvc?
is it possible?
Posted
Comments
Sergey Alexandrovich Kryukov 1-Aug-13 17:36pm    
What one model? send from where? what's the problem?...
—SA

1 solution

Use Jquery Ajax Post using JSON object

$.ajax({<br />
    url: '@Url.Action("MyAction")',<br />
    type: "POST",<br />
    data: { name : "Ram" },        <br />
    success: function (result) {<br />
        alert(result);<br />
    },<br />
    error: function (xhr, ajaxOptions, thrownError) {<br />
        alert(xhr.status);<br />
        alert(thrownError);<br />
    }<br />
});<br />

So your action method will be like

public ActionResult MyAction(MyModel mymodel)

Your model should contain the properties which you are passing from client side

Public class MyModel<br />
{<br />
     public string name { get;set;}<br />
}<br />


Thanks,
Ramanathan
 
Share this answer
 
Comments
Member 8454063 2-Aug-13 6:10am    
ok , but can i set results returned from my controller action to a field in my model?
for example in my model , i have a id field . can i set result to it?
Ramanathan Kannappan 2-Aug-13 12:21pm    
I guess you are using Razor view in MVC

Yes you can do it inside the Success by assign the value to the text box. If you don't want that in the UI put it in the Hidden field.

Inside success

$('hidMyModelId').val(result)

When submitting the page to the server it will go along with MyModel object.

Your Model is MyModel

@model MyModel ------ Model Declaration

@HideenFor(Model => Model.Id) - Model Bind Initially 0

after we assigned the id in the Ajax it will have the value
Member 8454063 6-Aug-13 13:38pm    
hello Ramanathan Kannappan
i did your answer. i put a hiddenfor and filled my field in model .but hiddenfor get null .

@Html.HiddenFor(m => m.id_city, new { @id = "hidMyModelid_city" })

$(document).ready(function () {


jQuery('#MyCombo').change(function(){

var str = document.getElementById('Mycombo').value;
var str1 = str.split(", ", 1).toString();


$.ajax({
url: 'someaction',
data: { countryy: str1 },
cache: false,
type: 'GET',
success: function (result) {
$('#hidMyModelid_city').val(result);


}
});


});




});

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900