Passing Model data from View to Controller and using its values

北城以北 提交于 2019-12-01 00:03:10

You have to pass the data back through your model to a separate controller method. This can be implemented as follows (I've simplified your code a bit, but the general implementation should work):

public class UploadViewModel
{    
    public string Course { get; set; }
    public string Title { get; set; }
}

Your GET Action:

public ActionResult Index()
{
    return View(new UploadViewModel());
}

Then in your view add the model and use it in the form, so that the data will be bound to your model. This can then be send back to your controller.

@model UploadViewModel
@using(Html.BeginForm())
{
    Course: @Html.TextBoxFor(s=>s.Course)
    Title: @Html.TextBoxFor(s=>s.Title)
    <input type="submit" value="Save file" />
}

Now get the values through a HttpPost action method in your controller:

[HttpPost]
public ActionResult Index(UploadViewModel model)
{
    //You can use model.Course and model.Title values now
}
Hüseyin Burak Karadag

There are two different way to send data controller. You must match the data you send in the Controller method

Using Ajax Post Method :

Will be create transfered object on javascript. object property name must be same to Model property name.

var objAjax = new Object();
     objAjax.Course = 'newCourse'; // Model prop is string type so this value must be string.
     objAjax.Title  = 'newTitle';  

   $.ajax('@Url.Action("MethodName", "ControllerName")', {
                type: 'POST',
                data: JSON.stringify(objAjax),
                contentType: "application/json",
                dataType: "json",
                traditional: true,
                success: function (returnData) {
                    // Do something when get success
                },
                error: function () {
                   // Do something when get an error
                }
            });


    [HttpPost]
    public ActionResult Index(UploadViewModel model)
    {
        //do something with the result
    }

Using FormPost Method

Html.BeginFom send all the data in the model to controller when press the submit button

ForExample

@using(Html.BeginForm())
{
    <div>
         // Your code 

        <div>
            <input type="submit" value="Go" />
        </div>
    </div>
}


[HttpPost]
public ActionResult Index(UploadViewModel model)
{
    //do someting
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!